Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Publish Dopplergeist research checkpoint, results, and implementation handoff
Cinna Davisc61d6294609b
diff --git a/.gitignore b/.gitignoreindex 8ea41c9..005a961 100644--- a/.gitignore+++ b/.gitignore@@ -2,6 +2,7 @@__pycache__/*.egg-info/.pytest_cache/+.artifacts/data/results/!data/.gitkeepdiff --git a/README.md b/README.mdindex 3d982cc..a36b5b1 100644--- a/README.md+++ b/README.md@@ -1,76 +1,89 @@-# Aircraft-acoustic geolocation reproduction--This project reconstructs the method in [colsto's video](https://www.youtube.com/watch?v=UytYrhYLOKI):-measure aircraft Doppler curves, constrain flight geometry, account for sound travel-time and terrain, and score candidate recording positions against actual ADS-B tracks.--**Status:** the complete local pipeline is implemented. Independent synthetic-audio-to-location runs recover the correct flights with 21.9 m error for two events-with unknown recording start, and 40.9 m error for a known-time one-minute event.-Real-world location verification is in progress; these synthetic errors do not-establish the video's real-world or national-search claims.--## Run--Python 3.11+ and `ffmpeg` are required. The current local environment is `.venv/`.+# DOPPLERGEIST++An independent reconstruction of the aircraft-sound geolocation method described+in [colsto's video](https://www.youtube.com/watch?v=UytYrhYLOKI). The pipeline+measures Doppler curves, compares them with historical ADS-B trajectories, accounts+for terrain and sound travel time, and ranks candidate recording positions.++**The target product is an MP3 upload followed by automatic event discovery and+location estimation, with 100 m error counting as success. That product is not+implemented yet.** The current CLI requires selected event windows, frequency+bands, flight data, and search configuration. A recording date or bounded time+window is also needed to select historical flight data; an undated audio file does+not itself provide that information.++## Verified results++| Case | Result | Scope |+| --- | --- | --- |+| Independent synthetic two-event audio | 21.89 m error; correct flight pair | Unknown recording start; three candidate regions; truth withheld from search |+| Independent synthetic 60-second event | 40.87 m error; correct flight | Known recording start; manually selected event |+| Original recording, two events | 43.86 m from published public-platform coordinate | Regional search; source-informed windows and bounds; reference coordinate is not surveyed ground truth |+| Original recording, faint 60-second event | 357.47 m from the same reference | Regional search; clock borrowed from the two-event result; does not meet the 100 m target |+| Separate 40-passage acoustic dataset | 33 detections; median speed error 6.85%, slant error 15.37% among detections | Annotation-assisted frequency bands; feature benchmark, not location validation |++The real two-event result has been reproduced with the faster CPA implementation+at the same winning point and score. No blind nationwide real-audio run has been+completed. Scores are ranking statistics, not calibrated probabilities.++Start with [the implementation handoff](docs/HANDOFF.md),+[current evidence](docs/PROGRESS.md), and [the reconstructed methodology](docs/METHODOLOGY.md).+Readable reports and plots are checked into [evidence/results](evidence/results).+Large inputs and complete outputs are in the+[checkpoint release](https://github.com/1337isnot1337/dopplergeist/releases/tag/checkpoint-2026-11-02).+See [artifact download and verification instructions](docs/ARTIFACTS.md).+The YouTube MP4 is intentionally excluded.++## Install and run++Python 3.11+ and `ffmpeg` are required. Python 3.14 was used for this checkpoint;+the recorded dependency versions are in [evidence/runtime.json](evidence/runtime.json).```bashpython -m venv .venv.venv/bin/pip install -e . pytest.venv/bin/python -m pytest -q.venv/bin/python scripts/make_synthetic_cases.py-.venv/bin/aircraft-geoloc run data/synthetic/two-events.json --output results/two-events-.venv/bin/aircraft-geoloc run data/synthetic/known-time-minute.json --output results/known-minute+.venv/bin/aircraft-geoloc run data/synthetic/two-events.json --output results/replay-two-events+.venv/bin/aircraft-geoloc run data/synthetic/known-time-minute.json --output results/replay-known-minute```-The generator writes truth separately. The search never loads it. Its audio-renderer transports an oscillator from emission time into receiver time without-calling the search's propagation model. Three widely separated regions contain-plausible flights; a known jet tests classification. Results include a ranked list-of points, the best point per flight combination, measured spectra, physical-model-overlays, filter counts, input hashes, and timings.+After restoring the release data, reproduce the real regional case with:-## Inputs and physical model+```bash+.venv/bin/aircraft-geoloc run data/source/reproduce-local.json --output results/replay-reference+```++Use a new output directory to preserve the original evidence. Historical reports+retain their original paths and implementation hashes; those paths are provenance,+not requirements for a new checkout. Configuration paths resolve relative to the+configuration file.-A JSON configuration identifies an audio/video file, flight-data files, event-windows/bands, terrain, a projected grid, filter tolerances and scoring settings.-Event speed, slant-distance and rest-frequency ranges may be set explicitly or-estimated from the measured curve. The video likewise uses manual event selection-and generous geometry bounds; fully unattended event discovery is not assumed.+## Inputs and modelCanonical CSV/Parquet columns are `flight_id,time_s,lat,lon,alt_m,typecode`.-Timestamps are Unix seconds or UTC ISO strings; heights and speeds are SI units.-Optional `east_mps,north_mps,up_mps` supply actual flight velocity. KML gx:Track-and readsb/ADSB.lol traces have importers. Gaps are split instead of interpolated-through. Unknown aircraft types are retained; only positively identified jet types-are removed. Readsb geometric-altitude fields and barometric fallbacks are labelled.+Timestamps are Unix seconds or UTC ISO strings; heights and speeds use SI units.+Optional `east_mps,north_mps,up_mps` provide flight velocity. KML `gx:Track` and+readsb/ADSB.lol traces have importers. Track gaps are split; extrapolation is+disallowed. Known-jet exclusion is configurable through the supplied type database.+The faint reference event requires retaining jets.-For aircraft position **x** at emission time tau and observer **o**, the code solves+For aircraft position **x** at emission time tau and receiver **o**, the solver uses:```t_received = tau + norm(x(tau) - o) / cfrequency = f0 * c / (c + dot(velocity(tau), x(tau)-o)/norm(x(tau)-o))```-Range rate is positive for a receding aircraft. A shared recording-clock adjustment-is fitted across all events; each event can adjust its rest frequency, but a second-event cannot shift independently in time. Scoring uses either normalized spectral-brightness along the predicted curves or residual against a measured ridge.--DEM rasters are sampled in their actual CRS. An optional geoid raster converts-orthometric ground height to the ellipsoidal datum used by GNSS aircraft heights.-Without a geoid, both aircraft and observer must use one common height datum.-Constant terrain is available for explicit controlled tests, not an implied DEM.--## Evidence and next work+Positive range rate means the aircraft is receding. All events share one recording+clock adjustment; rest frequency is fitted separately for each event. Scoring+uses either spectrogram contrast along the predicted curves or measured-ridge+residuals. Terrain and aircraft heights must use a consistent vertical datum;+the supplied real configurations include a geoid correction.-- [Current checkpoint](docs/PROGRESS.md)-- Source video captions, metadata, source frames and audio: `data/source/`-- Real paired research data: `scripts/fetch_research_data.py`-- Open historical ADS-B data: `scripts/fetch_adsblol_day.py YYYY-MM-DD`, then- `scripts/ingest_adsblol_day.py YYYY-MM-DD`-- Local reports: `results/synthetic-two-events/` and `results/synthetic-known-minute/`+## Sources-External recordings and large datasets stay outside Git. Downloaded research data-is checksum verified. The first real reproduction uses an area identified in the-video to validate data alignment before attempting a blind national search.+This is independently written code, not a release from the video author.+External data retain their own licenses and attribution requirements, described+in [data provenance](docs/DATA_SOURCES.md). No blanket license for those assets is+implied by this repository.diff --git a/docs/ARTIFACTS.md b/docs/ARTIFACTS.mdnew file mode 100644index 0000000..1164521--- /dev/null+++ b/docs/ARTIFACTS.md@@ -0,0 +1,49 @@+# Checkpoint artifacts++Release: [checkpoint-2026-11-02](https://github.com/1337isnot1337/dopplergeist/releases/tag/checkpoint-2026-11-02).+The repository is private; collaborators need repository access to download assets.++Readable result JSON, CSV and PNG files are mirrored under `evidence/results/` in+Git. Complete results, including spectral NPZ arrays, and all collected input data+are release assets. The original YouTube MP4 is deliberately excluded. The linked+reference WAV used by the tests remains included.++## Download and restore++From the repository root, with GitHub CLI authenticated:++```bash+mkdir -p .artifacts+gh release download checkpoint-2026-11-02 --repo 1337isnot1337/dopplergeist --dir .artifacts+(cd .artifacts && sha256sum -c SHA256SUMS)+for archive in .artifacts/*.tar.gz; do tar -xzf "$archive"; done+mkdir -p data/adsb/2026-09-08+cp .artifacts/v2026.09.08-planes-readsb-staging-0.tar.a? data/adsb/2026-09-08/+```++Restore into a clean checkout or preserve existing `data/` and `results/` first:+archive extraction writes those paths. The raw ADS-B parts are already compressed+internally and are uploaded unchanged. They are not independently extractable tar+files; the ingestion script streams their concatenation.++To download only enough for the regional reference replay, select these assets+with repeated `--pattern` arguments: `data-source.tar.gz`, `data-adsb-derived.tar.gz`,+and `data-terrain.tar.gz`. Download `manifest.json` and `SHA256SUMS` as well.+Verify selected files against their matching checksum lines before extracting.++## Manifest and transformations++[The checked-in manifest](../evidence/artifact-manifest.json) and release+`manifest.json` list each asset's size/hash and every contained file's path,+size/hash. Except for the two YouTube metadata JSON files, data and results are+byte-for-byte exports. Those metadata exports retain descriptive provenance but+omit transient media URLs, request headers and playback metadata; originals remain+local. Their original and exported hashes are both recorded.++Historical failed measurements, failed input downloads and logs are retained as+provenance; their presence is not a claim that they are usable inputs. Installed+virtual environments and Python caches are not research artifacts and are omitted.++`scripts/package_artifacts.py` builds the checksummed bundles without uploading+anything. It excludes MP4/video files and refuses to overwrite an existing bundle+directory. The published manifest is the inventory for this particular checkpoint.diff --git a/docs/DATA_SOURCES.md b/docs/DATA_SOURCES.mdnew file mode 100644index 0000000..9b6a38c--- /dev/null+++ b/docs/DATA_SOURCES.md@@ -0,0 +1,36 @@+# Data provenance and attribution++External materials retain their upstream rights and terms. This private checkpoint+does not relicense them, and contains no blanket license for third-party data.++- **Method/source:** colsto, [source video](https://www.youtube.com/watch?v=UytYrhYLOKI).+ The original description says no code or tools are being released. Captions are+ automatically generated and uncorrected. Still frames support parameter reading.+ The source MP4 is excluded from this repository and its release at the user's+ request; its original checksum remains in `data/source/source_manifest.json`.+- **Reference audio:** colsto, [Unknown location - raw audio](https://www.youtube.com/watch?v=4CxVxuMVkMc).+ The decoded WAV is retained for reproducibility; rights remain with its source.+- **Historical flight data:** [ADSB.lol globe_history_2026](https://github.com/adsblol/globe_history_2026),+ daily release `v2026.09.08-planes-readsb-staging-0`. The archive is distributed+ under ODbL; derived Parquet files retain that provenance. The upstream release+ metadata and ingestion reports are included.+- **Aircraft types:** [tar1090-db](https://github.com/wiedehopf/tar1090-db),+ `db/icao_aircraft_types.js`. The downloaded dictionary and normalized CSV are kept.+ [readsb format documentation](https://github.com/wiedehopf/readsb/blob/dev/README-json.md)+ explains trace field decoding.+- **Terrain:** Copernicus DEM GLO-30/GLO-90 public tiles and the EGM96 geoid raster+ from [PROJ data](https://cdn.proj.org/). Tile names/catalogue and cached files are+ retained; consult the providers' applicable attribution and redistribution terms.+- **Independent acoustic benchmark:** Praveen Pathak,+ [Aircraft speed and height from Doppler-shifted sound and flight-track data](https://zenodo.org/records/23424278),+ CC BY 4.0 according to the included Zenodo record. Its 40 recordings, flight+ tracks, measurements and supporting papers are checksum verified.+- **Regional evaluation reference:** the publicly mapped platform at+ [OspreyWatch nest 3916](https://app.osprey-watch.org/nest/3916). Its rounded+ coordinate is not surveyed microphone ground truth.++Original implementation: the Python package, synthetic renderer, tests and+orchestration scripts in this repository were written independently. The local+reference notes from the MIT-licensed+[Hermes implementation](https://github.com/mojomast/hermes-aircraft-doppler-geolocation)+are included as source investigation, not represented as our implementation.diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdnew file mode 100644index 0000000..6e9ad68--- /dev/null+++ b/docs/HANDOFF.md@@ -0,0 +1,83 @@+# Implementation handoff++## Read first++The user wants a full MP3-upload-to-location pipeline, with automatic Doppler-event+detection and approximately 100 m accuracy. The current CLI is a research+prototype with manually selected event windows. Do not describe it as a finished+upload product or treat the regional reference case as a nationwide validation.++The original implementation was not released. This repository contains our+independent implementation and the accumulated evidence, including unsuccessful+cases. [PROGRESS.md](PROGRESS.md) lists the verified results and limits.++## Suggested independent work areas++| Area | Main files | Concrete next result |+| --- | --- | --- |+| Event discovery | `audio.py`, new discovery module | Full-file event proposals without supplied windows/bands; harmonic deduplication; noise-only rejection; saved diagnostic evidence |+| Upload/orchestration | `cli.py`, `pipeline.py`, new interface | MP3 input, explicit recording date/time uncertainty, detection-to-search orchestration, progress and inconclusive results |+| Search scale | `search.py`, `terrain.py`, `tracks.py` | Bounded-memory tiled national search with preserved global timing and comparable ranking |+| Validation | `scripts/`, `tests/`, separate output directories | Independent real cases with withheld location, known audio clock, and reported misses/false matches |++These are suggested boundaries, not assignments. Coordinate before changing+shared files. Preserve existing evidence; write new runs to new directories and+record the implementation commit, input hashes, configuration and evaluation scope.++## Replay++Install as in the README and restore release assets using [ARTIFACTS.md](ARTIFACTS.md).+The real regional replay requires source, ADS-B-derived and terrain bundles:++```bash+.venv/bin/python -m pytest -q+.venv/bin/aircraft-geoloc run data/source/reproduce-local.json --output results/replay-reference+.venv/bin/aircraft-geoloc run data/source/reproduce-faint-alltypes-local.json --output results/replay-faint+.venv/bin/python scripts/benchmark_real_features.py+```++The benchmark script currently uses its fixed `results/real-feature-benchmark`+output path. Preserve/move that restored directory before rerunning the benchmark.+The full raw ADS-B archive is optional for these replays; the derived Parquet+files are sufficient. The original source MP4 is not uploaded, at the user's request.++## Important pitfalls++- The high-quality two-event case uses source-informed speed, slant and frequency+ bounds. Ridge extraction within selected bands is not event discovery.+- The faint event's best matching track is a CRJ9 jet. Removing every jet prevents+ this case from succeeding. Unknown aircraft types must also be retained.+- Its straight-pass fit suggests about 1 km slant, while the matching real track+ passes at about 4.9 km from the public reference. Tight filters derived from a+ straight-flight fit can exclude curved real trajectories.+- The faint-event result remains 357.47 m off. Its clock comes from the other+ two events; it is not an independent known-time success.+- The prominent raw-audio events are near 2156 s and 3076 s; some video interfaces+ display times offset by 3600 s. The faint raw-audio window is 1250–1310 s.+- Readsb traces in the daily tar are gzip compressed even when named `.json`.+ The type dictionary uses dictionaries such as `{"desc":"L2J","wtc":"M"}`.+- Geometric altitude and barometric fallback are labelled separately. Ground DEM+ orthometric height needs the configured geoid conversion for GNSS comparisons.+- `search.cpa_table_dense` is a retained test oracle. The production sparse CPA+ path must retain multiple local approaches and match the reference on small cases.+- Event clocks remain locked together. Independent shifts can manufacture a match.+- Search currently raises on an empty candidate set. An interface should translate+ that into an explicit inconclusive outcome without inventing a best location.+- The 40-passage dataset supplies helpful frequency annotations but lacks the+ explicit recorder-coordinate/audio-clock evidence needed here for location tests.++## Data inventory++- `data/source/`: source captions, transcript, still frames, reference WAV, configs,+ downloaded documentation, metadata and logs. Failed exploratory outputs are kept.+- `data/adsb/2026-09-08/`: raw daily archive parts, provenance, type database,+ 27,840,403-row CONUS prop/unknown Parquet, regional Parquet, and a 15-minute+ all-type CONUS Parquet for the faint case.+- `data/terrain/`: geoid, GLO-30 regional tile and cached GLO-90 tiles/catalogue.+- `data/research/`: checksum-verified Zenodo dataset, extracted recordings, tracks,+ annotations and papers.+- `data/synthetic/`: deterministic audio, tracks, configurations and separate truth.+- `results/`: complete successful, failed and exploratory output directories.++The release manifest records every exported file and its hash. Historical reports+retain original local paths; executable configs use relative input paths.diff --git a/docs/METHODOLOGY.md b/docs/METHODOLOGY.mdnew file mode 100644index 0000000..050a077--- /dev/null+++ b/docs/METHODOLOGY.md@@ -0,0 +1,88 @@+# Method reconstructed from the supplied video++The original implementation is unavailable. This is an independent reconstruction+of its described algorithm, with source observations separated from implementation+choices. The source is the supplied 1751.53-second MP4 and its timestamped captions.+Its SHA256 and local path are in `data/source/source_manifest.json`.++## Source observations++| Source time | Operation |+| --- | --- |+| 02:42-04:13 | Obtain an entire day's ADS-B flights; remove known jet aircraft using ICAO aircraft type designators, retaining unknown types. The shown client is `stiles/pyfr24`. |+| 04:18-07:48 | Lay a 200 m candidate grid; calculate the 3-D closest approach and the arrival time of its sound. The initial broad radius is 10 km. |+| 08:28-11:10 | Fit approximate constant-velocity Doppler shapes to bound speed and closest slant distance. Use generous ranges because actual aircraft turn and accelerate. |+| 10:35 frame | Event 1: 130-154 m/s, 4300-7800 m slant. Event 2: 88-110 m/s, 1390-4690 m slant. The measured separation is about 920 s. |+| 12:12 frame | Reject candidates with additional intervening propeller flyovers closer than max(event-1 slant, event-2 slant). No distance multiplier. This is a hearing heuristic, not a guaranteed audibility law. |+| 14:10-18:09 | Model exact curves from each actual trajectory, including sound travel time. Use radial velocity at emission, not reception. |+| 18:14-20:10 | Score spectral brightness along model curves. Sweep uncertain rest frequencies and a common placement of event 1. Event 2's placement remains locked to the flight-derived time difference. |+| 20:12-22:39 | Expand to 100 m scoring resolution, keep the best point per flight combination, then refine the leading geometry. |+| 22:53-24:11 | Known-time one-minute alternative: search relevant flight segments, score against a manually traced faint ridge rather than brightness. The stated known time is 20:37 UTC. |+| 26:09-28:09 | Assess persistence through finite high-pass attenuation, masking sounds and a phone link; discuss editing and stronger noise reduction. These demonstrations are not universal guarantees about arbitrary filters/codecs. |++The linked source audio is one hour long. Its prominent curves appear near 2156 s+and 3076 s; some source-video interfaces use a timeline 3600 s larger. Captions are+automatic and can contain errors; parameter values above were read from frames.++## Physical model and sign convention++Let the stationary receiver be o, aircraft position x(tau), velocity v(tau), and+sound speed c. Positions are three-dimensional WGS84 ECEF. All heights must first+be put in a consistent vertical datum.++```+r(tau) = norm(x(tau) - o)+u_r(tau) = dot(v(tau), x(tau)-o) / r(tau) [positive when receding]+t = tau + r(tau)/c+f(t) = f0 * c / (c + u_r(tau))+```++The solver inverts the arrival-time equation. Replacing tau with receiver time or+adding one constant delay changes the curve's shape and is not equivalent.++Closest approach minimizes r(tau), and its delayed CPA is tau_CPA+r_CPA/c. For+initial filtering the code calculates segment-wise minima of a densely sampled+trajectory; full scoring evaluates a cubic Hermite trajectory directly. Imported+flight gaps are split and no extrapolation is permitted.++## Reproduction choices and limits++- An equal-area CONUS grid (EPSG:5070) replaces the video's unspecified grid CRS.+ Its scale is not exactly one everywhere; corridor construction includes padding.+- Numeric spectrogram contrast removes stationary tonal baselines and normalizes+ the noise floor. The video does not specify its exact brightness normalization,+ FFT window or plotting color transformation; numerical score magnitudes therefore+ are not expected to equal its reported scores.+- Automatic tracing uses a bounded-slope Viterbi path, with optional supplied manual+ ridge CSV. This replaces manual visual measurements while retaining inspectable+ diagnostic plots. A forced best path is not automatically accepted as a detection.+- The rest tone may refer to a chosen harmonic, not necessarily the actual engine+ fundamental. It must remain consistent within that event.+- The common timing adjustment is selected by combined event score. Every event+ keeps its actual absolute flight clock; there is no independent second-event shift.+- Historical aircraft data uses the open ADSB.lol archive, not the video's paid+ Flightradar24 archive. Coverage, timing and geometry can differ between providers.+- Readsb's GNSS altitude is ellipsoidal. Its documented geometric field is used,+ with explicitly labelled interpolation or barometric fallback. Ground DEM heights+ receive a geoid correction where configured. Geoid model differences and GNSS/+ pressure altitude errors remain uncertainty sources.+- Constant sound speed, stationary microphone, source tone stability and adequate+ timestamp/sample-rate accuracy are assumptions. Wind, refraction, terrain+ obstruction, microphone response and changing propeller RPM can break matches.+- Silence is a configurable heuristic: missing ADS-B or a quieter aircraft can+ invalidate a hard rejection. Its separate counts are retained for ablation.+- Raw scores are ranking statistics, not calibrated location probabilities.++## Verification layers++1. Analytic constant-velocity solution versus the numerical retarded-time solver,+ including full Unix timestamps and no extrapolation.+2. Filter tests for silence, incorrect offsets, known jets, unknown types and gaps.+3. A scoring regression proving that a mismatched second event cannot get its own+ time adjustment; noise-only audio must not produce an accepted event.+4. An independent emission-domain audio renderer produces the synthetic cases;+ their ground truth is held out of the entire search.+5. The original source audio is measured and checked against historical tracks.+6. A separate 40-passage research dataset checks acoustic feature recovery against+ ADS-B reference speeds and ranges. It is not treated as an exact-location test+ because an explicit recorder coordinate and audio-sample clock are not supplied.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex a05198d..3b04b40 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,58 +1,71 @@-# Reproduction checkpoint--Objective: reconstruct the complete methodology in colsto's video UytYrhYLOKI,-and establish what works using reproducible end-to-end tests.--## Current evidence--- Source MP4: `/home/cinna/Downloads/I discovered a sound that leaks your exact location (and it's everywhere) - colsto (1080p).mp4` (1751.53 s).-- Downloaded the source video's English captions and metadata into `data/source/`.-- Candidate real validation source: https://zenodo.org/records/23424278,- 40 aircraft recordings with timestamped frequency measurements and ADS-B KMLs.-- Existing MIT implementation https://github.com/mojomast/hermes-aircraft-doppler-geolocation- implements ridge extraction and single-event candidate scoring, but not the full pipeline.--## Acceptance criteria--1. Document the source methodology, equations, assumptions and differences.-2. Implement audio ingestion, spectral measurements, ADS-B ingestion/type filtering,- terrain-aware candidate search, delay/Doppler modelling, event pairing and silence- filtering, locked multi-event scoring, refinement and reports.-3. Exercise audio-to-ranked-location runs with withheld synthetic truth, distractors,- unknown recording start, multiple events and a known-time short recording.-4. Run suitable real recordings against their actual independent flight tracks and- published recording-position evidence; report errors and failures without- substituting synthetic tests for real-world validation.-5. Leave exact commands, source manifests, tests and measured results.--## Implemented and checked--- Independent implementation in `src/aircraft_geoloc/`: canonical/KML/trace import,- WGS84 geometry, sound emission-time solve, Doppler, spectrograms, Viterbi ridge,- straight-pass measurements, flight corridor grids, DEM sampling, CPA tables,- multi-event time filters, silence filter, shared-clock brightness/ridge scoring,- grid refinement and plotted reports.-- `tests/test_physics.py`: 2 tests passed, including an independent analytic- constant-velocity solution at both small and full Unix timestamps.-- First full run: `results/synthetic-two-events/report.json`; correct flight pair,- 21.89 m location error and -0.343 s clock error. Input audio was generated by- an independent emission-domain renderer and truth was only read afterward.-- Synthetic one-minute known-time case is running.-- Downloaded all 40 paired research recordings with Zenodo checksum verification.-- Downloaded the video's linked one-hour source audio, and generated an overview- spectrogram in `data/source/reference-overview.png`.-- Video frame 10:35 gives first event 130-154 m/s and 4300-7800 m slant;- second 88-110 m/s and 1390-4690 m; offset 920 s. Frame 12:12 specifies- silence threshold max(CPA slant of the two events), with no multiplier.-- Source raw hour has event CPAs near 2156 s and 3076 s (source UI displays- times 3600 s later). The automatic tracker can attach to interfering tones;- narrow/manual windows remain part of the measured workflow, as in the video.-- Downloading the open 2026-09-08 ADS-B daily archive; recording year is currently- inferred from the video publication and must be checked against actual tracks.--## Next actions--Finish the short-clip test and filter regressions; improve/inspect reference ridge-measurements; ingest the historical archive, obtain aircraft type and elevation-data, and run the real reference recording end to end. Real geolocation is not-yet verified; the synthetic result does not establish the video's national claim.+# Checkpoint: 2026-11-02++The implementation campaign is paused at this handoff. Publishing the existing+code and artifacts does not mark the automatic-upload objective complete.++## Acceptance target++Upload an MP3, discover its usable Doppler events automatically, match historical+aircraft trajectories, and return a supported recording-location estimate. The+user accepts approximately 100 m error. Missing evidence must produce an explicit+inconclusive result rather than an unsupported precise coordinate.++## Implemented++- Audio/video decoding through ffmpeg; spectrogram contrast, bounded-slope Viterbi+ ridge extraction, straight-pass fitting, and noise/detection checks.+- CSV, Parquet, KML and readsb trajectory import; type classification, geometric+ altitude handling with labelled fallbacks, and track-gap splitting.+- WGS84 ECEF geometry, cubic Hermite trajectories, emission-time sound propagation,+ actual radial-velocity Doppler modelling, and no extrapolation.+- Terrain/geoid raster sampling, cached Copernicus GLO-90 coverage, corridor grids,+ sparse CPA search, event-offset and silence filters, locked multi-event scoring,+ refinement, and inspectable JSON/CSV/NPZ/PNG outputs.+- Download/ingestion scripts, an independent synthetic audio generator, and a+ 40-recording real feature benchmark.++## Evidence++| Artifact directory | Finding |+| --- | --- |+| `results/synthetic-two-events/` | Correct pair, 21.8855 m position error, -0.3426 s clock error |+| `results/synthetic-known-minute/` | Correct flight, 40.8744 m position error |+| `results/reference-local/` | PC12 `a1dfeb:1` + B350 `ace391:3`; 43.8585 m from mapped public-platform coordinate |+| `results/reference-local-fast/` | Same winning position and score as the preceding run; 46.26 s versus 103.09 s recorded runtime |+| `results/reference-faint-alltypes-local/` | CRJ9 `a38237`; 357.47 m error; fails the 100 m target |+| `results/real-feature-benchmark/` | 33/40 detections, zero processing errors; detected-case median absolute speed/slant errors 6.85%/15.37% |++The real two-event winning point is 40.8769317589, -73.5249822950. The comparison+point is the public nest-platform listing at 40.8766, -73.5247, whose precision and+physical accuracy are limited. The search used a regional box informed by the+source video. It is not a blind country-wide localization result.++The inferred recording start is 2026-09-08 20:17:29.662 UTC. The faint-event+configuration rounds that result to 20:17:30 UTC; it is not an independently+known recording clock. The video's stated 20:37 UTC and its various displayed+timelines have not been fully reconciled.++The feature benchmark uses supplied harmonic-band annotations and contains+substantial outliers. It validates acoustic measurements only. The synthetic+renderer does not call the search propagation model, and its truth is read only+for evaluation after search.++Fresh publication check: **11 tests passed**, covering analytic retarded-time+physics, full Unix timestamps, no extrapolation, repeated approaches, sparse/dense+CPA agreement, filters, shared event timing, noise rejection, altitude decoding,+and terrain/geoid sampling. These tests do not establish automatic discovery or+national-scale localization.++## Remaining work++1. Automatic full-recording event discovery and harmonic grouping, replacing manual+ event windows and frequency bands.+2. An MP3 upload interface and orchestration, including recording-date/time-window+ input when metadata do not establish it.+3. Reliable candidate selection under curved flight paths, source-frequency drift,+ low SNR, altitude uncertainty and missing flight data.+4. Scalable national search and independent real tests with withheld location and+ independently established recording times.+5. Confidence/ambiguity reporting and negative controls.++See [HANDOFF.md](HANDOFF.md) for suggested separable work and exact replay commands.diff --git a/evidence/configs/source/reproduce-faint-alltypes-local.json b/evidence/configs/source/reproduce-faint-alltypes-local.jsonnew file mode 100644index 0000000..63ce059--- /dev/null+++ b/evidence/configs/source/reproduce-faint-alltypes-local.json@@ -0,0 +1,58 @@+{+ "audio": "reference-recording.wav",+ "tracks": [+ "../adsb/2026-09-08/conus-alltypes-faint-window.parquet"+ ],+ "max_track_gap_s": 30,+ "terrain": {+ "rasters": [+ "../terrain/Copernicus_DSM_COG_10_N40_00_W074_00_DEM.tif"+ ],+ "geoid_raster": "../terrain/us_nga_egm96_15.tif"+ },+ "grid": {+ "bounds": [+ -73.59,+ 40.83,+ -73.47,+ 40.92+ ],+ "spacing_m": 200,+ "scoring_spacing_m": 100,+ "refine_spacing_m": 25,+ "refine_pairs": 5+ },+ "events": [+ {+ "start_s": 1250,+ "end_s": 1310,+ "band_hz": [+ 280,+ 530+ ],+ "max_slope_hz_s": 15,+ "max_up_slope_hz_s": 0.5,+ "speed_range_mps": [+ 50,+ 160+ ],+ "slant_range_m": [+ 500,+ 10000+ ],+ "f0_range_hz": [+ 300,+ 520+ ]+ }+ ],+ "filters": {+ "known_time_tolerance_s": 10+ },+ "scoring": {+ "mode": "ridge",+ "time_sweep_s": 5,+ "time_step_s": 0.5+ },+ "recording_start_utc": "2026-09-08T20:17:30Z"+}diff --git a/evidence/configs/source/reproduce-faint-local.json b/evidence/configs/source/reproduce-faint-local.jsonnew file mode 100644index 0000000..f9255d2--- /dev/null+++ b/evidence/configs/source/reproduce-faint-local.json@@ -0,0 +1,59 @@+{+ "audio": "reference-recording.wav",+ "tracks": [+ "../adsb/2026-09-08/reference-region.parquet"+ ],+ "type_database": "../adsb/2026-09-08/type-database.csv",+ "max_track_gap_s": 30,+ "terrain": {+ "rasters": [+ "../terrain/Copernicus_DSM_COG_10_N40_00_W074_00_DEM.tif"+ ],+ "geoid_raster": "../terrain/us_nga_egm96_15.tif"+ },+ "grid": {+ "bounds": [+ -73.59,+ 40.83,+ -73.47,+ 40.92+ ],+ "spacing_m": 200,+ "scoring_spacing_m": 100,+ "refine_spacing_m": 25,+ "refine_pairs": 5+ },+ "events": [+ {+ "start_s": 1250,+ "end_s": 1310,+ "band_hz": [+ 280,+ 530+ ],+ "max_slope_hz_s": 15,+ "max_up_slope_hz_s": 0.5,+ "speed_range_mps": [+ 65,+ 110+ ],+ "slant_range_m": [+ 500,+ 2000+ ],+ "f0_range_hz": [+ 374,+ 390+ ]+ }+ ],+ "filters": {+ "known_time_tolerance_s": 10+ },+ "scoring": {+ "mode": "ridge",+ "time_sweep_s": 5,+ "time_step_s": 0.5+ },+ "recording_start_utc": "2026-09-08T20:16:10Z"+}diff --git a/evidence/configs/source/reproduce-faint-recovered-clock.json b/evidence/configs/source/reproduce-faint-recovered-clock.jsonnew file mode 100644index 0000000..604fbe0--- /dev/null+++ b/evidence/configs/source/reproduce-faint-recovered-clock.json@@ -0,0 +1,59 @@+{+ "audio": "reference-recording.wav",+ "tracks": [+ "../adsb/2026-09-08/reference-region.parquet"+ ],+ "type_database": "../adsb/2026-09-08/type-database.csv",+ "max_track_gap_s": 30,+ "terrain": {+ "rasters": [+ "../terrain/Copernicus_DSM_COG_10_N40_00_W074_00_DEM.tif"+ ],+ "geoid_raster": "../terrain/us_nga_egm96_15.tif"+ },+ "grid": {+ "bounds": [+ -73.59,+ 40.83,+ -73.47,+ 40.92+ ],+ "spacing_m": 200,+ "scoring_spacing_m": 100,+ "refine_spacing_m": 25,+ "refine_pairs": 5+ },+ "events": [+ {+ "start_s": 1250,+ "end_s": 1310,+ "band_hz": [+ 280,+ 530+ ],+ "max_slope_hz_s": 15,+ "max_up_slope_hz_s": 0.5,+ "speed_range_mps": [+ 65,+ 110+ ],+ "slant_range_m": [+ 500,+ 2000+ ],+ "f0_range_hz": [+ 374,+ 390+ ]+ }+ ],+ "filters": {+ "known_time_tolerance_s": 10+ },+ "scoring": {+ "mode": "ridge",+ "time_sweep_s": 5,+ "time_step_s": 0.5+ },+ "recording_start_utc": "2026-09-08T20:17:30Z"+}diff --git a/evidence/configs/source/reproduce-local.json b/evidence/configs/source/reproduce-local.jsonnew file mode 100644index 0000000..a8ece95--- /dev/null+++ b/evidence/configs/source/reproduce-local.json@@ -0,0 +1,83 @@+{+ "audio": "reference-recording.wav",+ "tracks": [+ "../adsb/2026-09-08/reference-region.parquet"+ ],+ "type_database": "../adsb/2026-09-08/type-database.csv",+ "max_track_gap_s": 30,+ "terrain": {+ "rasters": [+ "../terrain/Copernicus_DSM_COG_10_N40_00_W074_00_DEM.tif"+ ],+ "geoid_raster": "../terrain/us_nga_egm96_15.tif"+ },+ "grid": {+ "bounds": [+ -73.59,+ 40.83,+ -73.47,+ 40.92+ ],+ "spacing_m": 200,+ "scoring_spacing_m": 100,+ "refine_spacing_m": 25,+ "refine_pairs": 5+ },+ "events": [+ {+ "start_s": 2100,+ "end_s": 2280,+ "band_hz": [+ 75,+ 190+ ],+ "max_slope_hz_s": 4,+ "max_up_slope_hz_s": 0.5,+ "speed_range_mps": [+ 130,+ 154+ ],+ "slant_range_m": [+ 4300,+ 7800+ ],+ "f0_range_hz": [+ 110,+ 116+ ]+ },+ {+ "start_s": 3040,+ "end_s": 3125,+ "band_hz": [+ 95,+ 185+ ],+ "max_slope_hz_s": 4,+ "max_up_slope_hz_s": 0.5,+ "speed_range_mps": [+ 88,+ 110+ ],+ "slant_range_m": [+ 1390,+ 4690+ ],+ "f0_range_hz": [+ 126,+ 133+ ]+ }+ ],+ "filters": {+ "offset_tolerance_s": 5,+ "silence": {+ "edge_margin_s": 100+ }+ },+ "scoring": {+ "mode": "brightness",+ "time_sweep_s": 5,+ "time_step_s": 0.5+ }+}diff --git a/evidence/configs/source/source_manifest.json b/evidence/configs/source/source_manifest.jsonnew file mode 100644index 0000000..31fbf1c--- /dev/null+++ b/evidence/configs/source/source_manifest.json@@ -0,0 +1,7 @@+{+ "video_path": "/home/cinna/Downloads/I discovered a sound that leaks your exact location (and it's everywhere) - colsto (1080p).mp4",+ "sha256": "7ead0ef0612cc79d32c8649ed344d6584731128ca01eadd8f3b631f0d911b843",+ "bytes": 654103997,+ "source_url": "https://www.youtube.com/watch?v=UytYrhYLOKI",+ "caption_type": "YouTube automatic English captions; uncorrected"+}diff --git a/evidence/configs/synthetic/known-time-minute.json b/evidence/configs/synthetic/known-time-minute.jsonnew file mode 100644index 0000000..c4173fe--- /dev/null+++ b/evidence/configs/synthetic/known-time-minute.json@@ -0,0 +1,47 @@+{+ "audio": "recording.wav",+ "tracks": [+ "tracks.csv"+ ],+ "type_database": "types.csv",+ "terrain": {+ "constant_m": 120+ },+ "grid": {+ "spacing_m": 200,+ "scoring_spacing_m": 100,+ "refine_spacing_m": 25,+ "refine_pairs": 3+ },+ "events": [+ {+ "start_s": 123,+ "end_s": 183,+ "band_hz": [+ 95,+ 185+ ],+ "speed_range_mps": [+ 60,+ 120+ ],+ "slant_range_m": [+ 1300,+ 2500+ ],+ "f0_range_hz": [+ 132,+ 138+ ]+ }+ ],+ "filters": {+ "known_time_tolerance_s": 5+ },+ "scoring": {+ "mode": "ridge",+ "time_sweep_s": 0.5,+ "time_step_s": 0.5+ },+ "recording_start_utc": 1790000000.0+}diff --git a/evidence/configs/synthetic/truth.json b/evidence/configs/synthetic/truth.jsonnew file mode 100644index 0000000..ac91a42--- /dev/null+++ b/evidence/configs/synthetic/truth.json@@ -0,0 +1,24 @@+{+ "lat": 40.03173,+ "lon": -100.01829,+ "elev_m": 120.0,+ "recording_start_time_s": 1790000000.0,+ "flight_ids": [+ "true-A",+ "true-B"+ ],+ "f0_hz": [+ 135.0,+ 115.0+ ],+ "events": [+ {+ "flight_id": "true-A",+ "center_emission_s": 150.0+ },+ {+ "flight_id": "true-B",+ "center_emission_s": 1070.0+ }+ ]+}diff --git a/evidence/configs/synthetic/two-events.json b/evidence/configs/synthetic/two-events.jsonnew file mode 100644index 0000000..f3d0922--- /dev/null+++ b/evidence/configs/synthetic/two-events.json@@ -0,0 +1,69 @@+{+ "audio": "recording.wav",+ "tracks": [+ "tracks.csv"+ ],+ "type_database": "types.csv",+ "terrain": {+ "constant_m": 120+ },+ "grid": {+ "spacing_m": 200,+ "scoring_spacing_m": 100,+ "refine_spacing_m": 25,+ "refine_pairs": 3+ },+ "events": [+ {+ "start_s": 65,+ "end_s": 250,+ "band_hz": [+ 95,+ 185+ ],+ "speed_range_mps": [+ 60,+ 120+ ],+ "slant_range_m": [+ 1300,+ 2500+ ],+ "f0_range_hz": [+ 132,+ 138+ ]+ },+ {+ "start_s": 985,+ "end_s": 1170,+ "band_hz": [+ 80,+ 155+ ],+ "speed_range_mps": [+ 50,+ 105+ ],+ "slant_range_m": [+ 1000,+ 2200+ ],+ "f0_range_hz": [+ 112,+ 118+ ]+ }+ ],+ "filters": {+ "offset_tolerance_s": 6,+ "silence": {+ "edge_margin_s": 100+ }+ },+ "scoring": {+ "mode": "brightness",+ "time_sweep_s": 3,+ "time_step_s": 0.5+ }+}diff --git a/evidence/runtime.json b/evidence/runtime.jsonnew file mode 100644index 0000000..09d8d35--- /dev/null+++ b/evidence/runtime.json@@ -0,0 +1,21 @@+{+ "python": "3.14.8",+ "platform": "Linux-7.2.10-arch1-1-x86_64-with-glibc2.44",+ "dependencies": {+ "numpy": "2.5.4",+ "scipy": "1.18.1",+ "pandas": "2.3.3",+ "soundfile": "0.14.0",+ "pyproj": "3.8.0",+ "rasterio": "1.5.2",+ "matplotlib": "3.11.2",+ "requests": "2.34.2",+ "pyarrow": "26.0.0",+ "pytest": "9.1.1",+ "setuptools": "84.0.0"+ },+ "ffmpeg": "ffmpeg version n9.0.2 Copyright (c) 2000-2026 the FFmpeg developers",+ "fresh_test_command": ".venv/bin/python -m pytest -q",+ "fresh_test_result": "11 passed in 1.95s",+ "date": "2026-11-02"+}diff --git a/scripts/ingest_adsblol_day.py b/scripts/ingest_adsblol_day.pyindex 17417fe..5b5ba75 100644--- a/scripts/ingest_adsblol_day.py+++ b/scripts/ingest_adsblol_day.py@@ -12,13 +12,19 @@ import pyarrow as paimport pyarrow.parquet as pqimport requests-from aircraft_geoloc.tracks import adsblol_frame+from aircraft_geoloc.tracks import adsblol_frame,unix_timeparser=argparse.ArgumentParser()parser.add_argument("date")+parser.add_argument("--bounds",type=float,nargs=4,default=[-125,24,-66,50],metavar=("WEST","SOUTH","EAST","NORTH"))+parser.add_argument("--output",default="conus-prop-unknown.parquet")+parser.add_argument("--keep-jets",action="store_true",help="Include jet types for the single-event ablation")+parser.add_argument("--time-range",nargs=2,metavar=("START_UTC","END_UTC"))args=parser.parse_args()root=Path(__file__).resolve().parents[1]directory=root/"data/adsb"/args.date+west,south,east,north=args.bounds+time_range=[unix_time(t) for t in args.time_range] if args.time_range else Nonetypes_path=root/"data/source/icao_aircraft_types.json"if not types_path.exists():r=requests.get("https://raw.githubusercontent.com/wiedehopf/tar1090-db/master/db/icao_aircraft_types.js",timeout=60)@@ -66,10 +72,11 @@ with io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream:raw=archive.extractfile(member).read()d=json.loads(gzip.decompress(raw) if raw[:2]==b"\x1f\x8b" else raw)stats["trace_files"]+=1- if engines.get(d.get("t",""))=="Jet":+ if not args.keep_jets and engines.get(d.get("t",""))=="Jet":stats["known_jets_removed"]+=1continue- trace=[p for p in d.get("trace",[]) if p[1] is not None and p[2] is not None and 24<=p[1]<=50 and -125<=p[2]<=-66]+ trace=[p for p in d.get("trace",[]) if p[1] is not None and p[2] is not None and south<=p[1]<=north and west<=p[2]<=east+ and (time_range is None or time_range[0]<=d["timestamp"]+p[0]<=time_range[1])]if not trace:stats["no_conus_points"]+=1continue@@ -81,11 +88,11 @@ with io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream:# aircraft cannot change a later parquet batch's physical type.schema=pa.schema([(c,pa.string() if c in ["flight_id","typecode","altitude_basis"] else pa.float64()) for c in frame.columns])batch=pa.Table.from_pandas(frame,schema=schema,preserve_index=False)- if writer is None:writer=pq.ParquetWriter(directory/"conus-prop-unknown.parquet",schema,compression="zstd")+ if writer is None:writer=pq.ParquetWriter(directory/args.output,schema,compression="zstd")writer.write_table(batch)stats["retained_aircraft"]+=1;stats["rows"]+=len(frame)stats["barometric_rows"]+=int((frame.altitude_basis=="barometric").sum())if stats["retained_aircraft"]%500==0:print(stats,flush=True)if writer:writer.close()-(directory/"ingestion-report.json").write_text(json.dumps(stats,indent=2)+"\n")+(directory/(Path(args.output).stem+"-ingestion-report.json")).write_text(json.dumps(stats,indent=2)+"\n")print(stats,flush=True)diff --git a/scripts/package_artifacts.py b/scripts/package_artifacts.pynew file mode 100644index 0000000..b0574d0--- /dev/null+++ b/scripts/package_artifacts.py@@ -0,0 +1,104 @@+"""Package the existing research checkpoint; no network or publishing side effects."""+import argparse+import hashlib+import io+import json+import os+from pathlib import Path+import tarfile+++def digest(path):+ with path.open("rb") as handle:+ return hashlib.file_digest(handle, "sha256").hexdigest()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("output", type=Path)+ args = parser.parse_args()+ root = Path(__file__).resolve().parents[1]+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ groups = {name: [] for name in (+ "data-source", "data-research", "data-terrain", "data-synthetic",+ "data-adsb-derived", "results")}+ raw = []+ excluded = []+ for folder in ("data", "results"):+ for path in sorted((root / folder).rglob("*")):+ if not path.is_file():+ continue+ relative = path.relative_to(root)+ if path.suffix.lower() in {".mp4", ".mkv", ".webm", ".mov", ".avi"}:+ excluded.append({"path": str(relative), "reason": "User excluded video"})+ continue+ if path.is_symlink():+ raise ValueError(f"Unexpected symlink: {relative}")+ if ".tar.a" in path.name and relative.parts[:2] == ("data", "adsb"):+ raw.append(path)+ continue+ group = "results" if folder == "results" else "-".join(relative.parts[:2])+ if group == "data-adsb":+ group = "data-adsb-derived"+ groups[group].append(path)+ manifest = {+ "checkpoint": "2026-11-02",+ "video_mp4_included": False,+ "reference_wav_included": True,+ "excluded": excluded,+ "assets": [],+ }+ metadata_keys = {+ "id", "title", "fulltitle", "description", "webpage_url", "uploader",+ "uploader_id", "uploader_url", "channel", "channel_id", "channel_url",+ "upload_date", "timestamp", "duration", "duration_string", "language",+ "license", "availability", "extractor", "extractor_key", "epoch",+ "width", "height", "fps", "asr", "audio_channels", "vcodec", "acodec",+ }+ for name, paths in groups.items():+ destination = output / f"{name}.tar.gz"+ files = []+ with tarfile.open(destination, "w:gz", compresslevel=1) as archive:+ for path in paths:+ relative = str(path.relative_to(root))+ entry = {"path": relative, "bytes": path.stat().st_size, "sha256": digest(path)}+ if path.name in {"video.info.json", "reference-recording.info.json"}:+ source = json.loads(path.read_text())+ clean = {key: value for key, value in source.items() if key in metadata_keys}+ clean["export_note"] = "Descriptive metadata only; transient media/request fields omitted."+ payload = (json.dumps(clean, indent=2) + "\n").encode()+ entry["original_bytes"] = entry["bytes"]+ entry["original_sha256"] = entry["sha256"]+ entry["bytes"] = len(payload)+ entry["sha256"] = hashlib.sha256(payload).hexdigest()+ entry["transformation"] = "descriptive_metadata_only"+ info = archive.gettarinfo(str(path), arcname=relative)+ info.size = len(payload)+ archive.addfile(info, io.BytesIO(payload))+ else:+ archive.add(path, arcname=relative, recursive=False)+ files.append(entry)+ manifest["assets"].append({"name": destination.name, "bytes": destination.stat().st_size,+ "sha256": digest(destination), "files": files})+ print(f"Packaged {destination.name}: {len(files)} files, {destination.stat().st_size} bytes", flush=True)+ for path in raw:+ destination = output / path.name+ os.link(path, destination)+ checksum = digest(destination)+ entry = {"path": str(path.relative_to(root)), "bytes": path.stat().st_size, "sha256": checksum}+ manifest["assets"].append({"name": destination.name, "bytes": entry["bytes"],+ "sha256": checksum, "restore_path": entry["path"], "files": [entry]})+ print(f"Linked {destination.name}: {entry['bytes']} bytes", flush=True)+ if any(asset["bytes"] >= 2 * 1024**3 for asset in manifest["assets"]):+ raise ValueError("An asset exceeds the release size limit; split before publishing")+ manifest_path = output / "manifest.json"+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")+ checksums = [f"{asset['sha256']} {asset['name']}" for asset in manifest["assets"]]+ checksums.append(f"{digest(manifest_path)} manifest.json")+ (output / "SHA256SUMS").write_text("\n".join(checksums) + "\n")+ print(f"Complete: {len(manifest['assets'])} assets; no video files included", flush=True)+++if __name__ == "__main__":+ main()diff --git a/src/aircraft_geoloc/pipeline.py b/src/aircraft_geoloc/pipeline.pyindex 2e2056e..6b0bab2 100644--- a/src/aircraft_geoloc/pipeline.py+++ b/src/aircraft_geoloc/pipeline.py@@ -10,7 +10,7 @@ import pandas as pdfrom .audio import measurefrom .geometry import eceffrom .search import cpa_table,pair_candidates,rank_candidates-from .terrain import Terrain,corridor_grid,refine_grid+from .terrain import Terrain,CopernicusTerrain,corridor_grid,refine_gridfrom .tracks import load_tracks,unix_time@@ -20,6 +20,11 @@ def dump(path,value):def run(config_path,output_dir):began=time.monotonic()+ code_root=Path(__file__).resolve().parents[1]+ code_digest=hashlib.sha256()+ for source in sorted(code_root.rglob("*.py")):+ code_digest.update(str(source.relative_to(code_root)).encode())+ code_digest.update(source.read_bytes())config_path=Path(config_path).resolve()config=json.loads(config_path.read_text())output=Path(output_dir).resolve()@@ -72,8 +77,9 @@ def run(config_path,output_dir):if not tracks:raise ValueError("No usable flight trajectories")ground=config["terrain"]- terrain=Terrain([local(p) for p in ground.get("rasters",[])],ground.get("constant_m"),- local(ground["geoid_raster"]) if ground.get("geoid_raster") else None)+ geoid=local(ground["geoid_raster"]) if ground.get("geoid_raster") else None+ terrain=(CopernicusTerrain(local(ground["copernicus_cache"]),geoid) if ground.get("copernicus_cache") else+ Terrain([local(p) for p in ground.get("rasters",[])],ground.get("constant_m"),geoid))grid=config.get("grid",{})coarse=grid.get("spacing_m",200)crs=grid.get("crs","EPSG:5070")@@ -136,17 +142,18 @@ def run(config_path,output_dir):digest=hashlib.file_digest(f,"sha256").hexdigest()provenance.append({"path":str(path.resolve()),"sha256":digest})report={"config":config,"measured_events":events,"imports":imports,"sources":provenance,+ "implementation_sha256":code_digest.hexdigest(),"coarse_filter_counts":counts,"scoring_filter_counts":fine_counts,"ranked_points":len(ranked),"flight_combinations":len(best_pairs),"best":ranked[0],"elapsed_s":time.monotonic()-began,"scoring_time_is_locked":True,"ground_truth_used_by_search":False}dump(output/"report.json",report)- plot_results(output,ranked,tracks,measurements)+ plot_results(output,ranked,tracks,measurements,c)print("Best:",json.dumps(ranked[0]),flush=True)return report-def plot_results(output,ranked,tracks,measurements):+def plot_results(output,ranked,tracks,measurements,c=343.0):import matplotlibmatplotlib.use("Agg")from matplotlib import pyplot as plt@@ -164,7 +171,7 @@ def plot_results(output,ranked,tracks,measurements):for i,(spec,ridge,weight,fit) in enumerate(measurements):best=ranked[0]track=lookup[best["flight_ids"][i]]- factor,_,_=track.acoustic(best["recording_start_time_s"]+spec.time,ecef(best["lat"],best["lon"],best["elev_m"]))+ factor,_,_=track.acoustic(best["recording_start_time_s"]+spec.time,ecef(best["lat"],best["lon"],best["elev_m"]),c)fig,ax=plt.subplots(figsize=(10,4),layout="constrained")ax.pcolormesh(spec.time,spec.frequency,spec.contrast,shading="auto",cmap="magma",vmin=0,vmax=6)ax.plot(spec.time,best["f0_hz"][i]*factor,color="cyan",lw=1.1,label="Best physical model")diff --git a/src/aircraft_geoloc/search.py b/src/aircraft_geoloc/search.pyindex 9146a44..2261f9b 100644--- a/src/aircraft_geoloc/search.py+++ b/src/aircraft_geoloc/search.py@@ -9,7 +9,7 @@ from scipy.spatial import cKDTreefrom .geometry import ecef-def cpa_table(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256):+def cpa_table_dense(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256):"""Vectorized piecewise-linear CPA prefilter; supports repeated local passes.This is the inexpensive first stage. Final scoring evaluates the interpolated@@ -20,16 +20,30 @@ def cpa_table(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256)for track in tracks:t = np.unique(np.r_[np.arange(track.time[0],track.time[-1],step_s),track.time[-1]])pos = track.position(t)- delta = np.diff(pos,axis=0)+ # Prune trajectory segments outside this observer tile before forming a+ # point-by-segment tensor. Keep original segment endpoints/times so a gap+ # between retained pieces cannot invent a straight-line flight.+ lower=observers.min(axis=0)-max_distance+ upper=observers.max(axis=0)+max_distance+ keep=np.all((np.minimum(pos[:-1],pos[1:])<=upper)&+ (np.maximum(pos[:-1],pos[1:])>=lower),axis=1)+ if not np.any(keep):+ continue+ first,last=pos[:-1][keep],pos[1:][keep]+ t0,t1=t[:-1][keep],t[1:][keep]+ delta = last-firstlength2 = np.sum(delta**2,axis=1)- supported = np.isfinite(cKDTree(pos).query(observers,+ endpoints=np.concatenate((first,last))+ near_box=np.all((observers>=endpoints.min(axis=0)-max_distance)&+ (observers<=endpoints.max(axis=0)+max_distance),axis=1)+ nearby=np.flatnonzero(near_box)+ supported = np.isfinite(cKDTree(endpoints).query(observers[nearby],distance_upper_bound=max_distance+np.sqrt(length2.max()))[0])- for base in range(0,len(points),chunk_size):- indices = np.flatnonzero(supported[base:base+chunk_size])+base- if not len(indices):- continue+ active=nearby[supported]+ for base in range(0,len(active),chunk_size):+ indices = active[base:base+chunk_size]obs = observers[indices]- residual = pos[:-1][None,:,:]-obs[:,None,:]+ residual = first[None,:,:]-obs[:,None,:]fraction = np.clip(-np.einsum("bsi,si->bs",residual,delta)/np.maximum(length2,1e-12),0,1)dist2 = np.sum((residual+fraction[:,:,None]*delta[None,:,:])**2,axis=2)# A zero-velocity segment or path endpoint is not evidence of a full@@ -43,7 +57,7 @@ def cpa_table(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256)last_time = -np.inffor k in peaks:distance = np.sqrt(dist2[j,k])- when = t[k]+fraction[j,k]*(t[k+1]-t[k])+ when = t0[k]+fraction[j,k]*(t1[k]-t0[k])if distance > max_distance or when-last_time < step_s*1.1:continuelast_time = when@@ -54,6 +68,69 @@ def cpa_table(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256)return pd.DataFrame(rows,columns=["point_id","flight_id","emission_time","receive_time","distance_m","speed_mps"])+def cpa_table(tracks,points,max_distance,c=343.0,step_s=2.0,chunk_size=512):+ """Spatial-radius CPA graph, retaining every local pass without dense tensors.++ The radius includes two complete sample steps beyond the audible envelope,+ so both neighbours of an in-range sampled minimum are present. Each minimum+ is refined on its two actual adjacent segments. The dense reference above+ provides an independent regression oracle for this search optimization.+ """+ observers=ecef(points.lat.to_numpy(),points.lon.to_numpy(),points.elev_m.to_numpy())+ point_ids=points.point_id.to_numpy(dtype=int)+ rows=[]+ for track in tracks:+ t=np.unique(np.r_[np.arange(track.time[0],track.time[-1],step_s),track.time[-1]])+ pos=track.position(t)+ max_step=np.max(np.linalg.norm(np.diff(pos,axis=0),axis=1))+ near=np.flatnonzero(np.all((observers>=pos.min(axis=0)-max_distance)&+ (observers<=pos.max(axis=0)+max_distance),axis=1))+ tree=cKDTree(pos)+ for base in range(0,len(near),chunk_size):+ chosen=near[base:base+chunk_size]+ obs=observers[chosen]+ neighbours=tree.query_ball_point(obs,max_distance+2*max_step,return_sorted=True)+ counts=np.fromiter((len(a) for a in neighbours),dtype=int,count=len(neighbours))+ if not counts.sum():continue+ sample=np.concatenate(neighbours).astype(int)+ observer_index=np.repeat(np.arange(len(obs)),counts)+ distance2=np.sum((pos[sample]-obs[observer_index])**2,axis=1)+ previous=np.r_[False,(observer_index[1:]==observer_index[:-1])&(sample[1:]==sample[:-1]+1)]+ following=np.r_[(observer_index[1:]==observer_index[:-1])&(sample[1:]==sample[:-1]+1),False]+ minima=(previous&following&(distance2<=np.r_[np.inf,distance2[:-1]])&+ (distance2<np.r_[distance2[1:],np.inf]))+ indices=np.flatnonzero(minima)+ if not len(indices):continue+ k=sample[indices]+ oi=observer_index[indices]+ # Project onto both neighbouring polyline edges, never across a+ # missing interval or between unrelated flight passes.+ first=np.stack((pos[k-1],pos[k]),axis=1)+ last=np.stack((pos[k],pos[k+1]),axis=1)+ delta=last-first+ residual=first-obs[oi,None,:]+ fraction=np.clip(-np.sum(residual*delta,axis=2)/np.maximum(np.sum(delta**2,axis=2),1e-12),0,1)+ d2=np.sum((residual+fraction[:,:,None]*delta)**2,axis=2)+ edge=np.argmin(d2,axis=1)+ n=np.arange(len(k))+ distance=np.sqrt(d2[n,edge])+ start=np.where(edge==0,k-1,k)+ when=t[start]+fraction[n,edge]*(t[start+1]-t[start])+ speed=np.linalg.norm(track.speed_vector(when),axis=1)+ for j in np.flatnonzero(distance<=max_distance):+ rows.append({"point_id":int(point_ids[chosen[oi[j]]]),"flight_id":track.id,+ "emission_time":float(when[j]),"receive_time":float(when[j]+distance[j]/c),+ "distance_m":float(distance[j]),"speed_mps":float(speed[j])})+ result=pd.DataFrame(rows,columns=["point_id","flight_id","emission_time","receive_time","distance_m","speed_mps"])+ if not result.empty:+ # A CPA exactly at a sample can be proposed twice under roundoff.+ result=result.sort_values(["point_id","flight_id","emission_time"])+ duplicate=(result.point_id.eq(result.point_id.shift())&result.flight_id.eq(result.flight_id.shift())&+ result.emission_time.diff().abs().lt(step_s*1.1))+ result=result[~duplicate].reset_index(drop=True)+ return result++def filter_event(table, event, time_origin=None, time_tolerance=5.0):speed, distance = event["speed_range_mps"],event["slant_range_m"]keep = table.speed_mps.between(*speed) & table.distance_m.between(*distance)diff --git a/src/aircraft_geoloc/terrain.py b/src/aircraft_geoloc/terrain.pyindex 25fa53f..f75266b 100644--- a/src/aircraft_geoloc/terrain.py+++ b/src/aircraft_geoloc/terrain.py@@ -20,7 +20,12 @@ class Terrain:for raster in self.rasters:transform = Transformer.from_crs("EPSG:4326", raster.crs, always_xy=True)x, y = transform.transform(lon.ravel(), lat.ravel())- values = np.ma.asarray(list(raster.sample(zip(x, y), masked=True)))[:, 0]+ col,row=(~raster.transform) @ (np.asarray(x),np.asarray(y))+ col,row=np.floor(col).astype(int),np.floor(row).astype(int)+ inside=(col>=0)&(col<raster.width)&(row>=0)&(row<raster.height)+ values=np.ma.masked_all(len(col))+ data=raster.read(1,masked=True)+ values[inside]=data[row[inside],col[inside]]valid = ~np.ma.getmaskarray(values)flat = elevation.ravel()flat[valid] = np.asarray(values)[valid]@@ -33,6 +38,53 @@ class Terrain:return elevation+class CopernicusTerrain:+ """Public GLO-90 DSM tiles, cached locally; water-only missing tiles are zero.++ At this CONUS search scope the published tile catalogue covers land. An absent+ tile is accepted as ocean only when it is absent from that catalogue, not when+ a network download fails. EGM2008 DSM heights use the configured geoid grid.+ """+ def __init__(self,cache,geoid_path=None):+ import requests+ self.cache=Path(cache)+ self.cache.mkdir(parents=True,exist_ok=True)+ self.session=requests.Session()+ catalog=self.cache/"tileList.txt"+ if not catalog.exists():+ response=self.session.get("https://copernicus-dem-90m.s3.amazonaws.com/tileList.txt",timeout=60)+ response.raise_for_status();catalog.write_text(response.text)+ self.catalog=set(catalog.read_text().splitlines())+ self.geoid=Terrain([geoid_path]) if geoid_path else None++ def sample(self,lat,lon):+ lat,lon=np.broadcast_arrays(lat,lon)+ shape=lat.shape+ lat,lon=lat.ravel(),lon.ravel()+ degrees=np.column_stack((np.floor(lat).astype(int),np.floor(lon).astype(int)))+ tiles,inverse=np.unique(degrees,axis=0,return_inverse=True)+ height=np.zeros(len(lat))+ for index,(north,east) in enumerate(tiles):+ tag=f"Copernicus_DSM_COG_30_{'N' if north>=0 else 'S'}{abs(north):02d}_00_{'E' if east>=0 else 'W'}{abs(east):03d}_00_DEM"+ if tag not in self.catalog and tag+"/" not in self.catalog:+ continue+ path=self.cache/(tag+".tif")+ if not path.exists():+ import fcntl+ with path.with_suffix(".lock").open("a") as lock:+ fcntl.flock(lock,fcntl.LOCK_EX)+ if not path.exists():+ url=f"https://copernicus-dem-90m.s3.amazonaws.com/{tag}/{tag}.tif"+ r=self.session.get(url,timeout=120);r.raise_for_status()+ temporary=path.with_suffix(".part");temporary.write_bytes(r.content);temporary.replace(path)+ selected=inverse==index+ sampler=Terrain([path])+ height[selected]=sampler.sample(lat[selected],lon[selected])+ for raster in sampler.rasters:raster.close()+ if self.geoid:height+=self.geoid.sample(lat,lon)+ return height.reshape(shape)++def corridor_grid(tracks, events, spacing_m, terrain, crs="EPSG:5070", bounds=None, time_origin=None):"""Only materialize grid cells near plausible aircraft segments.@@ -41,6 +93,7 @@ def corridor_grid(tracks, events, spacing_m, terrain, crs="EPSG:5070", bounds=No"""forward = Transformer.from_crs("EPSG:4326", crs, always_xy=True)inverse = Transformer.from_crs(crs, "EPSG:4326", always_xy=True)+ clipbox=forward.transform_bounds(*bounds,densify_pts=21) if bounds else Nonecells = []for track in tracks:for event in events:@@ -67,12 +120,26 @@ def corridor_grid(tracks, events, spacing_m, terrain, crs="EPSG:5070", bounds=No# EPSG:5070 grid scale is close to unity over CONUS; 10% padding# plus an anchor gap protects corridor coverage under distortion.pad = radius * 1.45 + spacing_m+ if clipbox:+ left,bottom,right,top=clipbox+ ax,ay=anchors[:,0]*spacing_m,anchors[:,1]*spacing_m+ anchors=anchors[(ax>=left-pad)&(ax<=right+pad)&(ay>=bottom-pad)&(ay<=top+pad)]+ if not len(anchors):+ continuesize = int(np.ceil(pad / spacing_m))dx, dy = np.meshgrid(np.arange(-size, size+1), np.arange(-size,size+1))offsets = np.column_stack((dx.ravel(), dy.ravel()))offsets = offsets[np.linalg.norm(offsets, axis=1) * spacing_m <= pad]+ event_cells=[]for anchor in anchors:- cells.append(anchor + offsets)+ expanded=anchor+offsets+ if clipbox:+ ex,ey=expanded[:,0]*spacing_m,expanded[:,1]*spacing_m+ expanded=expanded[(ex>=left-spacing_m)&(ex<=right+spacing_m)&+ (ey>=bottom-spacing_m)&(ey<=top+spacing_m)]+ if len(expanded):event_cells.append(expanded)+ if event_cells:+ cells.append(np.unique(np.concatenate(event_cells),axis=0))if not cells:raise ValueError("No flight segments meet event speed/time bounds")cells = np.unique(np.concatenate(cells), axis=0)diff --git a/tests/test_physics.py b/tests/test_physics.pyindex 2d5ef21..b5d1704 100644--- a/tests/test_physics.py+++ b/tests/test_physics.py@@ -33,3 +33,47 @@ def test_cpa_and_no_extrapolation():assert abs(cpa["distance_m"]-slant)<0.001factor,_,_=track.acoustic(np.array([1_789_999_800.0,1_790_000_200.0]),observer)assert np.all(np.isnan(factor))+++def test_vectorized_cpa_matches_independent_continuous_minimum():+ import pandas as pd+ from aircraft_geoloc.search import cpa_table+ track,observer,slant=straight_track(1_790_000_000)+ points=pd.DataFrame({"point_id":[0,1],"lat":[40,30],"lon":[-100,-80],"elev_m":[100,0]})+ table=cpa_table([track],points,5000)+ assert list(table.point_id)==[0]+ assert abs(table.distance_m.iloc[0]-slant)<0.01+ assert abs(table.emission_time.iloc[0]-1_790_000_000)<0.001+++def test_repeated_flyovers_are_not_collapsed_to_one_global_cpa():+ import pandas as pd+ from aircraft_geoloc.search import cpa_table+ observer=ecef(40,-100,100)+ t=np.arange(-20,100.1,0.5)+ xyz=observer+np.column_stack((4000*np.sin(2*np.pi*t/80),np.full(len(t),1300),np.full(len(t),700)))+ inverse=Transformer.from_crs("EPSG:4978","EPSG:4979",always_xy=True)+ lon,lat,h=inverse.transform(*xyz.T)+ track=Track("repeated",t,lat,lon,h)+ points=pd.DataFrame({"point_id":[0],"lat":[40],"lon":[-100],"elev_m":[100]})+ table=cpa_table([track],points,1800)+ assert len(table)==3+ assert_allclose(sorted(table.emission_time),[0,40,80],atol=0.01)+++def test_sparse_cpa_graph_agrees_with_dense_reference_on_curved_track():+ import pandas as pd+ from aircraft_geoloc.search import cpa_table,cpa_table_dense+ observer=ecef(40,-100,100)+ t=np.arange(-80,81,0.5)+ xyz=observer+np.column_stack((90*t+0.03*t*t,1200+0.1*t*t,900+0.5*t))+ inverse=Transformer.from_crs("EPSG:4978","EPSG:4979",always_xy=True)+ lon,lat,h=inverse.transform(*xyz.T)+ track=Track("curve",t,lat,lon,h)+ points=pd.DataFrame({"point_id":np.arange(15),"lat":np.linspace(39.99,40.01,15),+ "lon":np.linspace(-100.01,-99.99,15),"elev_m":100})+ fast=cpa_table([track],points,5000).sort_values("point_id")+ slow=cpa_table_dense([track],points,5000).sort_values("point_id")+ assert list(fast.point_id)==list(slow.point_id)+ assert_allclose(fast.emission_time,slow.emission_time,atol=1e-9)+ assert_allclose(fast.distance_m,slow.distance_m,atol=1e-8)diff --git a/tests/test_terrain.py b/tests/test_terrain.pynew file mode 100644index 0000000..bfa0ffd--- /dev/null+++ b/tests/test_terrain.py@@ -0,0 +1,21 @@+import numpy as np+import pytest+import rasterio+from rasterio.transform import from_origin++from aircraft_geoloc.terrain import Terrain+++def test_raster_height_and_geoid_are_combined_and_missing_coverage_is_rejected(tmp_path):+ paths=[]+ for name,data in [("ground",np.array([[10,20],[30,40]],dtype="float32")),+ ("geoid",np.full((2,2),-30,dtype="float32"))]:+ path=tmp_path/(name+".tif")+ with rasterio.open(path,"w",driver="GTiff",width=2,height=2,count=1,dtype="float32",+ crs="EPSG:4326",transform=from_origin(-101,41,1,1)) as raster:+ raster.write(data,1)+ paths.append(path)+ terrain=Terrain([paths[0]],geoid_path=paths[1])+ assert np.allclose(terrain.sample([40.5,39.5],[-100.5,-99.5]),[-20,10])+ with pytest.raises(ValueError,match="coverage missing"):+ terrain.sample([45],[-110])