Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Use improved Doppler detection by default (#411)
Cinna Davisd98a4f26afa9
diff --git a/README.md b/README.mdindex eb1497e..d1186c8 100644--- a/README.md+++ b/README.md@@ -99,6 +99,8 @@ dopplergeist discover \--output results/my-discovery```+Discovery uses the same detector as automatic analysis. It decodes the recording at two sample rates, groups related measured tracks into acoustic proposals, and retains the individual tracks for subsequent analysis. A proposal alone does not establish aircraft identity.+This scans the full recording locally without downloading ADS-B archives. Inspect `results/my-discovery/summary.json` and the saved `discovery/` diagnostics. See [Automatic audio discovery](docs/AUDIO_DISCOVERY.md) for detector details and options.For configured research workflows, `dopplergeist run` and `dopplergeist measure` remain available; see [Methodology](docs/METHODOLOGY.md).diff --git a/docs/AUDIO_DISCOVERY.md b/docs/AUDIO_DISCOVERY.mdindex 7f7d70f..b0ba2a8 100644--- a/docs/AUDIO_DISCOVERY.md+++ b/docs/AUDIO_DISCOVERY.md@@ -1,193 +1,11 @@# Automatic audio-event discovery-`discover_events(recording, output_dir=None, settings=None)` consumes the-`IntakeRecording` from intake and returns shared-contract `DetectedEvent`-dictionaries. The normal call supplies no time windows, frequency bands, aircraft-IDs, search locations or truth. It scans all decoded samples with fixed 120 s-chunks / 60 s overlap, a 2 s Hann spectrum at 0.5 s hops and 40–1600 Hz coverage-(clamped below decoded Nyquist). Working memory is bounded by chunk size; a disk-cache holds the complete recording. Inputs under one spectral window return [].+`dopplergeist discover input.mp3 --output results/new-audio-scan` scans the complete recording for acoustic moving-tone proposals. Automatic analysis uses the same discovery path. No event windows, frequency bands, aircraft identities or location hints are required.-Time-whitened spectral contrast suppresses persistent stationary tones. Local-maxima are linked with bounded motion, short missing spans and local slope-continuity. Minimum duration/support, resolved downward frequency change,-distributed motion and jump checks reject noise paths and switching stationary-tones. Duplicate overlapping chunk ridges merge before grouping harmonics. Both-integer ratios and rational ratios (e.g. measured 2f and 3f with an absent-fundamental) count as one independent event. The lowest measured harmonic is the-representative ridge; no fundamental is invented. Harmonic count denotes distinct-measured ratios, including fragmented traces of the same harmonic only once.-Harmonic grouping is optional consolidation: a ridge without a compatible-partner remains a single-ridge event candidate. The detector does not require a-second harmonic.+Intake decodes the original audio at 4 kHz and 24 kHz. Discovery combines ridge tracking and time-frequency sequence analysis, verifies measured tracks, and groups related tracks into proposals. The lower-rate ridge finder remains an internal component of this detector. The two decodes are checked against the same source hash.-The output preserves recording-relative ridge samples and weights, measured-window/band, harmonic-group identity, contrast/support, spectral resolution and-uncertainty diagnostics. Resolution is not a calibrated error interval; no raw-quality score is a probability. No compulsory straight-flight speed, slant or-source-frequency estimate constrains downstream search. These are **acoustic-moving-tone proposals**, with aircraft identity unconfirmed. Association must-reject unsupported proposals and count harmonic groups once.+`discovery/discovery.json` contains the input hash, detector settings, canonical proposal intervals and measured child tracks. Tracks belonging to a proposal share a `harmonic_group_id`; downstream association should count the group once while retaining its measured tracks. Times are relative to the first decoded sample. `--plot-summary` renders a track overview and `--plot-event-details` renders individual track plots. Use a new output directory for each run.-In the current real one-hour upload, automatic discovery produced 15 independent-groups: 14 have one observed ridge and one has three. This is a useful reminder-that harmonic grouping can consolidate evidence when multiple bands are-recorded, but a single-ridge candidate must remain eligible for downstream-assessment. The audio-only discovery result does not confirm aircraft identity-or recording location.+Discovery uses fixed settings. A track is acoustic evidence, not proof that the source is an aircraft or that the pitch change was caused by physical motion. Missed, fragmented, merged and spurious proposals remain possible. Runtime, memory and disk use depend on recording length and content. Historical results from earlier discovery versions do not establish this detector's general performance or location accuracy.-With output_dir, discovery saves `discovery.json` (all events, settings, chunk-counts, original harmonic ridges and input hash), `discovery.png` (overview), and-per-event CSV plus spectrogram PNG. Each spectrogram image is limited to a chunk's-span; the full measured ridge remains in JSON/CSV. Existing discovery outputs-are refused. A reproducible whole-file entry point is:--```bash-dopplergeist discover input.mp3 --output results/new-audio-scan-```--The installed CLI records the source hash, settings, measured events and chunk-counts in its output. It does not consume evaluation labels. Run post-hoc-evaluation in a separate process. Use a new output directory for every run.-Pass `--plot-summary` for the overview or `--plot-event-details` for individual-spectrograms; plotting is off by default in the CLI.-The checkout-only `scripts/discover_audio.py` additionally records its Git state,-code hash, runtime and peak RSS for research comparisons.--Development evidence before DG-02 controls: full synthetic WAV (1180 s), 2-proposals spanning both planted passes, 7.24 s / 238044 KiB peak RSS; full public-reference WAV (3600.1845 s after decode), 8 proposals, 31.05 s / 249528 KiB peak-RSS. The two prominent known passes are covered, but are fragmented into multiple-proposals; the documented faint pass is missed. Six proposals do not cover either documented pass center; some appear to be-fragments of the same pass. Their identities remain unverified. They are not-labelled aircraft or certified false alarms. No-complete real event annotation exists to calculate reference precision/recall.-Earlier v1/v2 diagnostics preserve a missed synthetic event and excess proposals.-These are development checks, not independent location/nationwide validation.--Known limits: fixed spectral scale and minimum duration can miss steep/short,-faint, low-frequency or high-frequency events. A single wide ridge can fragment-across missing spans, and acoustically similar harmonic sources can be grouped-ambiguously. No algorithm can establish aircraft identity solely from an arbitrary-matching synthetic chirp. The existing real recording has no independently-verified UTC clock. This implementation does not establish 100 m localization.--Focused tests: `PYTHONPATH=src .venv/bin/python -m pytest -q tests/test_discovery.py`.-They cover complete-file seams, harmonic grouping including an absent fundamental,-simultaneous unrelated events, noise/stationary/upward-sweep rejection, short-unsupported clips, and crossfading stationary tones. Fixed-setting DG-02 corpus-results are recorded separately in the audio evidence handoff.--Fixed-code DG-02 control check at discovery commit `4a49646`: all 14 opaque-input-cases processed, 8 planted events found, 0 misses and 0 false alarms at event-IoU >= 0.3. Both the development and public deterministic held_out split find-4/4 events. Noise, stationary, upward electronic sweep and short clips produce-no event; harmonic, overlapping and MP3 positives are retained. Detection ran-through the label-free subprocess runner; a later process read truth for scoring.-No detector/settings changes followed the control run. These controls have no-eligible location cases and do not establish real-aircraft identity or accuracy.--Additional unchanged-code public-audio check: all 40 complete passage WAVs process-without errors; 28 have at least one proposal, 12 have none, 102 proposals total.-The run never supplied their frequency annotations. These counts do not establish-true aircraft-event recall/precision: fragments and incidental sources remain-unverified. Every prediction is saved under evidence/audio/w1-20261102/public40-4a49646.--Fragment follow-up: compatible disjoint ridge fragments can join across at most-20 s when the gap is at most 35% of the combined observed span, both endpoint-slopes descend, the observed frequency drop/rate is compatible with those slopes,-and each endpoint has only one compatible continuation. Competing continuations-remain separate. No frequency samples are invented across missing intervals;-harmonic comparison excludes unsupported spans. `fragment_count` and-`max_observed_gap_s` retain missing-support evidence, and `fragment_links` records-accepted/ambiguous continuations with reasons. This is a tonal continuity-hypothesis; it does not prove a flight identity.--`quality.frequency_sigma_hz` is the integration consumer's canonical robust-loss-scale, with `frequency_uncertainty_hz` retained for compatibility. Both currently-carry the same resolution/robust-deviation diagnostic, with no statistical or-probability calibration implied by the field name. Matching applies its >=1 Hz-loss-scale floor. Later tests against the already public DG-02 controls are-regressions, not newly held-out accuracy evidence.--Sensitivity follow-up lowers the global seed contrast threshold from3.0 to2.5.-At this setting the full synthetic recording still yields2 groups, with first-ridge support extended from143–180.5s to119–196s. The reference emits16 proposals,-including a short1265.5–1282s ridge in the documented faint passage; post-run-comparison with the archived manual ridge gives median absolute difference-0.692Hz over23 points (90th percentile2.139Hz). This is acoustic overlap with an-existing development measurement, not independently known aircraft or location-truth. Fourteen known synthetic controls retain8 hits/0 misses/0 false alarms.-The extra unverified reference proposals remain a matching/search cost. Earlier-3.0-threshold evidence and the faint-pass miss stay preserved; no held-out or-100m localization claim follows from this development tuning.--Discovery returns all accepted independent groups; it has no global two- or-three-event maximum. Four- and six-episode generated audio regressions check that-later events survive and harmonics count once. These audio-only controls test-retention, not geographic accuracy. The per-frame peak budget remains an explicit-bounded-analysis setting, and unsupported or missed tones are not a completeness-guarantee. The contrast 2.5 settings are frozen for the new public-camera batch.--## Experimental acoustic episodes--The installed `discover` command and the checkout script support an explicit-`--experimental-episodes` switch. This switch selects-`dopplergeist.episode_discovery` for acoustic reports. Without the switch, both-commands retain the scanner described above. The automatic analysis and upload-workflow also retain that scanner.--Run the experimental scanner on a real recording:--```bash-dopplergeist discover input.mp3 --output results/new-episode-scan \- --experimental-episodes --plot-summary-```--Use a new output directory for each run. For a wider frequency range, run:--```bash-dopplergeist discover input.mp3 --output results/new-wide-episode-scan \- --experimental-episodes --max-frequency-hz 6000 --plot-summary-```--The experimental settings default to 40–1600 Hz, a 2-second spectral window,-and a 0.5-second hop. The commands accept `--min-frequency-hz`,-`--max-frequency-hz`, `--window-s`, `--hop-s`, and `--detailed-candidates` only-with `--experimental-episodes`. The checkout script accepts the same switch:--```bash-PYTHONPATH=src python scripts/discover_audio.py input.mp3 \- --output results/new-research-episode-scan --experimental-episodes-```--Experimental intake selects a decoding rate that supports the requested band.-It explicitly uses the FFmpeg resampler with a 64-tap filter and a 0.95 cutoff.-The default scanner retains its existing decoding command. Unsupported source-coverage and analysis limits produce explicit errors.--### Outputs and compatibility--Default discovery retains its existing artifact, which has no explicit-`schema_version` field. Experimental discovery writes-`discovery/discovery.json` with `schema_version: 2`, a canonical `episodes`-catalog, and measured `events` children. Episode records reference their measured-children. Gaps remain gaps, and an inferred fundamental does not create measured-ridge samples. Coverage, settings, counts, rejection diagnostics, and code identity-remain available in the artifact.--The child events retain the shared `DetectedEvent` contract. Numeric quality-fields include `episode_model_version`, `episode_frequency_scale`, and-`matching_eligible`. The matching adapter supports these recorded children and-retains its legacy behavior for version-1 events. Brief episodes without enough-samples remain evidence for acoustic review. The experimental command does not-run a location search or enable these episodes in automatic upload jobs.--The [frozen real-recording comparison](ACOUSTIC_EPISODES_REPORT.md) retains every-input, including zeros and regressions. Its labels `new` and `default` refer to-the experimental implementation with its original settings. They do not name-the current product default. Six baseline reference groups had no retained-measurement within the report's overlap tolerance, including the documented faint-passage. Runtime also increased on the measured-comparison. The evidence does not establish improved aircraft recall, source-identity, or location accuracy.+[Earlier discovery documentation and historical results](archive/AUDIO_DISCOVERY_LEGACY.md) are preserved separately.diff --git a/docs/PRODUCT.md b/docs/PRODUCT.mdindex 28bb1a6..6edeb9f 100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@ -327,15 +327,8 @@ refinement; `refine_finalists` (default 5) limits physical sensitivityrefinement. Unassessed retained approaches prevent an affirmative confidencedecision.-For chunk-boundary checks on real recordings, an operator can set-`"discovery": {"chunk_s": 120.0, "overlap_s": 60.0}` in this private configuration.-These are the only discovery overrides supported by the product adapter. The-existing detector validates the overlap and chunk constraints; spectral bands,-acceptance thresholds and other scientific settings keep their defaults. The-actual settings and analyzed chunks are saved in `discovery/discovery.json`, and-the operator configuration hash is retained in provenance. This configuration is-not an upload-request field. A chunk-size comparison must rerun detection and the-pipeline; it cannot reuse final candidates as if discovery had run again.+Discovery uses fixed detector settings. The settings and measured proposals are+saved in `discovery/discovery.json`; custom discovery settings are rejected.An operator can add `"spectral_comparison": {}` to save a separate`spectral-comparison.json` artifact after refinement. This optional stage readsdiff --git a/docs/archive/AUDIO_DISCOVERY_LEGACY.md b/docs/archive/AUDIO_DISCOVERY_LEGACY.mdnew file mode 100644index 0000000..9ab37ac--- /dev/null+++ b/docs/archive/AUDIO_DISCOVERY_LEGACY.md@@ -0,0 +1,195 @@+> Historical documentation: this describes earlier discovery implementations and obsolete command-line options. It does not describe the current default.++# Automatic audio-event discovery++`discover_events(recording, output_dir=None, settings=None)` consumes the+`IntakeRecording` from intake and returns shared-contract `DetectedEvent`+dictionaries. The normal call supplies no time windows, frequency bands, aircraft+IDs, search locations or truth. It scans all decoded samples with fixed 120 s+chunks / 60 s overlap, a 2 s Hann spectrum at 0.5 s hops and 40–1600 Hz coverage+(clamped below decoded Nyquist). Working memory is bounded by chunk size; a disk+cache holds the complete recording. Inputs under one spectral window return [].++Time-whitened spectral contrast suppresses persistent stationary tones. Local+maxima are linked with bounded motion, short missing spans and local slope+continuity. Minimum duration/support, resolved downward frequency change,+distributed motion and jump checks reject noise paths and switching stationary+tones. Duplicate overlapping chunk ridges merge before grouping harmonics. Both+integer ratios and rational ratios (e.g. measured 2f and 3f with an absent+fundamental) count as one independent event. The lowest measured harmonic is the+representative ridge; no fundamental is invented. Harmonic count denotes distinct+measured ratios, including fragmented traces of the same harmonic only once.+Harmonic grouping is optional consolidation: a ridge without a compatible+partner remains a single-ridge event candidate. The detector does not require a+second harmonic.++The output preserves recording-relative ridge samples and weights, measured+window/band, harmonic-group identity, contrast/support, spectral resolution and+uncertainty diagnostics. Resolution is not a calibrated error interval; no raw+quality score is a probability. No compulsory straight-flight speed, slant or+source-frequency estimate constrains downstream search. These are **acoustic+moving-tone proposals**, with aircraft identity unconfirmed. Association must+reject unsupported proposals and count harmonic groups once.++In the current real one-hour upload, automatic discovery produced 15 independent+groups: 14 have one observed ridge and one has three. This is a useful reminder+that harmonic grouping can consolidate evidence when multiple bands are+recorded, but a single-ridge candidate must remain eligible for downstream+assessment. The audio-only discovery result does not confirm aircraft identity+or recording location.++With output_dir, discovery saves `discovery.json` (all events, settings, chunk+counts, original harmonic ridges and input hash), `discovery.png` (overview), and+per-event CSV plus spectrogram PNG. Each spectrogram image is limited to a chunk's+span; the full measured ridge remains in JSON/CSV. Existing discovery outputs+are refused. A reproducible whole-file entry point is:++```bash+dopplergeist discover input.mp3 --output results/new-audio-scan+```++The installed CLI records the source hash, settings, measured events and chunk+counts in its output. It does not consume evaluation labels. Run post-hoc+evaluation in a separate process. Use a new output directory for every run.+Pass `--plot-summary` for the overview or `--plot-event-details` for individual+spectrograms; plotting is off by default in the CLI.+The checkout-only `scripts/discover_audio.py` additionally records its Git state,+code hash, runtime and peak RSS for research comparisons.++Development evidence before DG-02 controls: full synthetic WAV (1180 s), 2+proposals spanning both planted passes, 7.24 s / 238044 KiB peak RSS; full public+reference WAV (3600.1845 s after decode), 8 proposals, 31.05 s / 249528 KiB peak+RSS. The two prominent known passes are covered, but are fragmented into multiple+proposals; the documented faint pass is missed. Six proposals do not cover either documented pass center; some appear to be+fragments of the same pass. Their identities remain unverified. They are not+labelled aircraft or certified false alarms. No+complete real event annotation exists to calculate reference precision/recall.+Earlier v1/v2 diagnostics preserve a missed synthetic event and excess proposals.+These are development checks, not independent location/nationwide validation.++Known limits: fixed spectral scale and minimum duration can miss steep/short,+faint, low-frequency or high-frequency events. A single wide ridge can fragment+across missing spans, and acoustically similar harmonic sources can be grouped+ambiguously. No algorithm can establish aircraft identity solely from an arbitrary+matching synthetic chirp. The existing real recording has no independently+verified UTC clock. This implementation does not establish 100 m localization.++Focused tests: `PYTHONPATH=src .venv/bin/python -m pytest -q tests/test_discovery.py`.+They cover complete-file seams, harmonic grouping including an absent fundamental,+simultaneous unrelated events, noise/stationary/upward-sweep rejection, short+unsupported clips, and crossfading stationary tones. Fixed-setting DG-02 corpus+results are recorded separately in the audio evidence handoff.++Fixed-code DG-02 control check at discovery commit `4a49646`: all 14 opaque-input+cases processed, 8 planted events found, 0 misses and 0 false alarms at event+IoU >= 0.3. Both the development and public deterministic held_out split find+4/4 events. Noise, stationary, upward electronic sweep and short clips produce+no event; harmonic, overlapping and MP3 positives are retained. Detection ran+through the label-free subprocess runner; a later process read truth for scoring.+No detector/settings changes followed the control run. These controls have no+eligible location cases and do not establish real-aircraft identity or accuracy.++Additional unchanged-code public-audio check: all 40 complete passage WAVs process+without errors; 28 have at least one proposal, 12 have none, 102 proposals total.+The run never supplied their frequency annotations. These counts do not establish+true aircraft-event recall/precision: fragments and incidental sources remain+unverified. Every prediction is saved under evidence/audio/w1-20261102/public40-4a49646.++Fragment follow-up: compatible disjoint ridge fragments can join across at most+20 s when the gap is at most 35% of the combined observed span, both endpoint+slopes descend, the observed frequency drop/rate is compatible with those slopes,+and each endpoint has only one compatible continuation. Competing continuations+remain separate. No frequency samples are invented across missing intervals;+harmonic comparison excludes unsupported spans. `fragment_count` and+`max_observed_gap_s` retain missing-support evidence, and `fragment_links` records+accepted/ambiguous continuations with reasons. This is a tonal continuity+hypothesis; it does not prove a flight identity.++`quality.frequency_sigma_hz` is the integration consumer's canonical robust-loss+scale, with `frequency_uncertainty_hz` retained for compatibility. Both currently+carry the same resolution/robust-deviation diagnostic, with no statistical or+probability calibration implied by the field name. Matching applies its >=1 Hz+loss-scale floor. Later tests against the already public DG-02 controls are+regressions, not newly held-out accuracy evidence.++Sensitivity follow-up lowers the global seed contrast threshold from3.0 to2.5.+At this setting the full synthetic recording still yields2 groups, with first+ridge support extended from143–180.5s to119–196s. The reference emits16 proposals,+including a short1265.5–1282s ridge in the documented faint passage; post-run+comparison with the archived manual ridge gives median absolute difference+0.692Hz over23 points (90th percentile2.139Hz). This is acoustic overlap with an+existing development measurement, not independently known aircraft or location+truth. Fourteen known synthetic controls retain8 hits/0 misses/0 false alarms.+The extra unverified reference proposals remain a matching/search cost. Earlier+3.0-threshold evidence and the faint-pass miss stay preserved; no held-out or+100m localization claim follows from this development tuning.++Discovery returns all accepted independent groups; it has no global two- or+three-event maximum. Four- and six-episode generated audio regressions check that+later events survive and harmonics count once. These audio-only controls test+retention, not geographic accuracy. The per-frame peak budget remains an explicit+bounded-analysis setting, and unsupported or missed tones are not a completeness+guarantee. The contrast 2.5 settings are frozen for the new public-camera batch.++## Experimental acoustic episodes++The installed `discover` command and the checkout script support an explicit+`--experimental-episodes` switch. This switch selects+`dopplergeist.episode_discovery` for acoustic reports. Without the switch, both+commands retain the scanner described above. The automatic analysis and upload+workflow also retain that scanner.++Run the experimental scanner on a real recording:++```bash+dopplergeist discover input.mp3 --output results/new-episode-scan \+ --experimental-episodes --plot-summary+```++Use a new output directory for each run. For a wider frequency range, run:++```bash+dopplergeist discover input.mp3 --output results/new-wide-episode-scan \+ --experimental-episodes --max-frequency-hz 6000 --plot-summary+```++The experimental settings default to 40–1600 Hz, a 2-second spectral window,+and a 0.5-second hop. The commands accept `--min-frequency-hz`,+`--max-frequency-hz`, `--window-s`, `--hop-s`, and `--detailed-candidates` only+with `--experimental-episodes`. The checkout script accepts the same switch:++```bash+PYTHONPATH=src python scripts/discover_audio.py input.mp3 \+ --output results/new-research-episode-scan --experimental-episodes+```++Experimental intake selects a decoding rate that supports the requested band.+It explicitly uses the FFmpeg resampler with a 64-tap filter and a 0.95 cutoff.+The default scanner retains its existing decoding command. Unsupported source+coverage and analysis limits produce explicit errors.++### Outputs and compatibility++Default discovery retains its existing artifact, which has no explicit+`schema_version` field. Experimental discovery writes+`discovery/discovery.json` with `schema_version: 2`, a canonical `episodes`+catalog, and measured `events` children. Episode records reference their measured+children. Gaps remain gaps, and an inferred fundamental does not create measured+ridge samples. Coverage, settings, counts, rejection diagnostics, and code identity+remain available in the artifact.++The child events retain the shared `DetectedEvent` contract. Numeric quality+fields include `episode_model_version`, `episode_frequency_scale`, and+`matching_eligible`. The matching adapter supports these recorded children and+retains its legacy behavior for version-1 events. Brief episodes without enough+samples remain evidence for acoustic review. The experimental command does not+run a location search or enable these episodes in automatic upload jobs.++The [frozen real-recording comparison](ACOUSTIC_EPISODES_REPORT.md) retains every+input, including zeros and regressions. Its labels `new` and `default` refer to+the experimental implementation with its original settings. They do not name+the current product default. Six baseline reference groups had no retained+measurement within the report's overlap tolerance, including the documented faint+passage. Runtime also increased on the measured+comparison. The evidence does not establish improved aircraft recall, source+identity, or location accuracy.diff --git a/package.nix b/package.nixindex e175d3a..08b692c 100644--- a/package.nix+++ b/package.nix@@ -17,6 +17,7 @@ python314.pkgs.buildPythonApplication {dependencies = with python314.pkgs; [numpyscipy+ numbapandassoundfilepyprojdiff --git a/pyproject.toml b/pyproject.tomlindex 30f9577..469e712 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -24,7 +24,7 @@ classifiers = [license = "PolyForm-Noncommercial-1.0.0"license-files = ["LICENSE", "licenses/MIT-legacy.txt", "src/dopplergeist/web/leaflet-license.txt"]requires-python = ">=3.11"-dependencies = ["numpy", "scipy", "pandas", "soundfile", "pyproj", "rasterio", "matplotlib", "requests", "pyarrow", "shapely>=2.0"]+dependencies = ["numpy", "scipy", "numba>=0.68.1", "pandas", "soundfile", "pyproj", "rasterio", "matplotlib", "requests", "pyarrow", "shapely>=2.0"][project.urls]Homepage = "https://github.com/1337isnot1337/DOPPLERGEIST"@@ -34,7 +34,6 @@ Issues = "https://github.com/1337isnot1337/DOPPLERGEIST/issues"Releases = "https://github.com/1337isnot1337/DOPPLERGEIST/releases"[project.optional-dependencies]-advanced = ["numba>=0.68.1"]test = ["pytest>=8"][project.scripts]diff --git a/scripts/discover_advanced.py b/scripts/discover_advanced.pydeleted file mode 100644index 9ea5a62..0000000--- a/scripts/discover_advanced.py+++ /dev/null@@ -1,28 +0,0 @@-import argparse-import json-from pathlib import Path-import time--from dopplergeist.advanced_discovery import discover-from dopplergeist.intake import intake_recording-from dopplergeist.resource_usage import process_peak_rss_kib---def main():- parser = argparse.ArgumentParser(description="Discover moving acoustic contours in a recording")- parser.add_argument("audio", type=Path)- parser.add_argument("--output", type=Path, required=True)- args = parser.parse_args()- args.output.mkdir(parents=True, exist_ok=False)- start = time.monotonic()- recording = intake_recording(args.audio, args.output / "intake", sample_rate_hz=4000)- auxiliary = intake_recording(args.audio, args.output / "intake_high", sample_rate_hz=24000)- result = discover(recording, args.output, "ridge_dp_accel_broad_final_v25", aux_recording=auxiliary)- result.update(recording=recording.metadata, runtime_s=time.monotonic() - start,- peak_rss_kib=process_peak_rss_kib())- (args.output / "predictions.json").write_text(json.dumps(result, indent=2, allow_nan=False) + "\n")- print(json.dumps({"proposals": len(result["events"]), "output": str(args.output / "predictions.json")}))---if __name__ == "__main__":- main()diff --git a/scripts/discover_audio.py b/scripts/discover_audio.pyindex 0ee1e4e..ba750ab 100644--- a/scripts/discover_audio.py+++ b/scripts/discover_audio.py@@ -4,7 +4,6 @@ No annotations, coordinates, flight IDs or per-case frequency/time hints are reaEvaluate its output against withheld labels in a separate process."""import argparse-from dataclasses import asdictimport hashlibimport jsonfrom pathlib import Path@@ -23,53 +22,32 @@ def main():help="render the recording-level ridge overview plot")parser.add_argument("--plot-event-details", action="store_true",help="render one spectrogram PNG per discovered event (slower)")- parser.add_argument("--experimental-episodes", action="store_true",- help="use experimental episode reporting instead of the standard detector")- parser.add_argument("--min-frequency-hz", type=float)- parser.add_argument("--max-frequency-hz", type=float)- parser.add_argument("--window-s", type=float)- parser.add_argument("--hop-s", type=float)- parser.add_argument("--detailed-candidates", action="store_true", help="bounded rejected-candidate measurements")args = parser.parse_args()- overrides = {name: getattr(args, name) for name in- ("min_frequency_hz", "max_frequency_hz", "window_s", "hop_s")- if getattr(args, name) is not None}- if not args.experimental_episodes and (overrides or args.detailed_candidates):- parser.error("Frequency, window, hop and detailed-candidate options require --experimental-episodes")- intake_options, discovery_options = {}, {}- if args.experimental_episodes:- from dopplergeist import episode_discovery as discovery- settings = discovery.DiscoverySettings(**overrides)- intake_options = dict(sample_rate_hz=discovery.required_sample_rate(settings), resample_filter_size=64)- discovery_options = dict(settings=settings, detailed_candidates=args.detailed_candidates)- else:- from dopplergeist import discovery- settings = discovery.DiscoverySettings()+ from dopplergeist import discovery+ settings = discovery.DiscoverySettings()output = Path(args.output)output.mkdir(parents=True, exist_ok=False)began = time.monotonic()- recording = intake_recording(args.audio, output / "intake", **intake_options)+ recording = intake_recording(args.audio, output / "intake")events = discovery.discover_events(recording, output_dir=output / "discovery",plot_summary=args.plot_summary,- plot_event_details=args.plot_event_details, **discovery_options)+ plot_event_details=args.plot_event_details)root = Path(__file__).resolve().parents[1]sources = sorted((root / "src" / "dopplergeist").glob("*.py"))code_hash = hashlib.sha256()for path in sources:code_hash.update(path.name.encode())code_hash.update(path.read_bytes())+ diagnostics = json.loads((output / "discovery/discovery.json").read_text())result = {"recording": recording.metadata, "time_status": recording.time_status,- "settings": asdict(settings), "events_found": len(events),+ "settings": diagnostics["settings"], "sequence_settings": diagnostics["sequence_settings"],+ "events_found": len(events),"events": [{k: event[k] for k in ("event_id", "start_s", "end_s", "band_hz", "quality")} for event in events],"runtime_s": time.monotonic() - began, "peak_rss_kib": process_peak_rss_kib(),"code_sha256": code_hash.hexdigest(),"git_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip(),"working_tree": subprocess.check_output(["git", "status", "--short"], cwd=root, text=True).strip(),"scope": "Blind acoustic discovery only; no aircraft association or location estimate"}- if args.experimental_episodes:- result.update(experimental_episodes=True, discovery_schema_version=2,- canonical_proposals=len({e["harmonic_group_id"] for e in events}),- measured_child_tracks=len(events))(output / "summary.json").write_text(json.dumps(result, indent=2, allow_nan=False) + "\n")print(json.dumps(result, indent=2))diff --git a/src/dopplergeist/advanced_discovery.py b/src/dopplergeist/advanced_discovery.pyindex ff85e3d..4ccc9c5 100644--- a/src/dopplergeist/advanced_discovery.py+++ b/src/dopplergeist/advanced_discovery.py@@ -123,7 +123,7 @@ def decoded_sample_rate_hz(variant):return 4000def discover(recording, output, variant, aux_recording=None):- events = baseline.discover_events(recording, output_dir=output / 'baseline-tracks', plot_summary=False, plot_event_details=False)+ events = baseline._discover_baseline_events(recording, output_dir=output / 'baseline-tracks', plot_summary=False, plot_event_details=False)proposals, decisions = catalog(events, 'coherent_adaptive' if variant.startswith('ridge_dp') else variant)diagnostics = []if variant.startswith('ridge_dp'):diff --git a/src/dopplergeist/automatic.py b/src/dopplergeist/automatic.pyindex e4ce989..ef1c163 100644--- a/src/dopplergeist/automatic.py+++ b/src/dopplergeist/automatic.py@@ -19,11 +19,11 @@ def _digest(path):def _audio_identity(request, config):- modules = ("intake.py", "discovery.py", "audio.py", "contracts.py")+ modules = ("intake.py", "discovery.py", "advanced_discovery.py", "audio.py", "contracts.py")return {"request": request, "source_sha256": _digest(request["audio_path"]),"discovery_settings": config.get("discovery", {}),"modules": {name: _digest(Path(__file__).parent / name) for name in modules},- "packages": {name: version(name) for name in ("numpy", "scipy")}}+ "packages": {name: version(name) for name in ("numpy", "scipy", "numba")}}def _save_audio_checkpoint(output, request, config):@@ -112,11 +112,13 @@ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: Nif search_workers is not None and (type(search_workers) is not int or search_workers < 1):return finish("failed", "invalid_configuration", "search_workers must be a positive integer.")if not isinstance(discovery_options, dict) or discovery_options.keys() - {"chunk_s", "overlap_s"}:- return finish("failed", "invalid_configuration", "Operator discovery settings support only chunk_s and overlap_s.")+ return finish("failed", "invalid_configuration", "Only default discovery settings are supported.")try:discovery_settings = DiscoverySettings(**discovery_options)except (TypeError, ValueError) as exc:return finish("failed", "invalid_configuration", f"Invalid operator discovery settings: {exc}")+ if discovery_settings != DiscoverySettings():+ return finish("failed", "invalid_configuration", "Custom discovery settings are not supported.")spectral_options = config.get("spectral_comparison")spectral_keys = {"time_sweep_s", "time_step_s", "frequency_step_hz", "expansion_s","window_s", "hop_s", "max_window_s", "max_modes", "max_event_clock_trials",diff --git a/src/dopplergeist/cli.py b/src/dopplergeist/cli.pyindex 7f8d13e..201a276 100644--- a/src/dopplergeist/cli.py+++ b/src/dopplergeist/cli.py@@ -107,14 +107,6 @@ def main():discover.add_argument("--output",required=True,help="New directory for the scan and diagnostics")discover.add_argument("--plot-summary",action="store_true",help="Render a recording-level ridge overview")discover.add_argument("--plot-event-details",action="store_true",help="Render a spectrogram for each proposal")- discover.add_argument("--experimental-episodes",action="store_true",- help="Use experimental acoustic episode reporting; not used by automatic location jobs")- discover.add_argument("--min-frequency-hz",type=float,help="Experimental lower frequency bound (default: 40)")- discover.add_argument("--max-frequency-hz",type=float,help="Experimental upper frequency bound (default: 1600)")- discover.add_argument("--window-s",type=float,help="Experimental spectral window in seconds (default: 2)")- discover.add_argument("--hop-s",type=float,help="Experimental spectral hop in seconds (default: 0.5)")- discover.add_argument("--detailed-candidates",action="store_true",- help="Save bounded rejected-candidate measurements; requires --experimental-episodes")analyze=sub.add_parser("analyze",help="Automatically locate aircraft audio, or explain insufficient evidence")analyze.add_argument("audio")analyze.add_argument("--start-utc",help="Earliest UTC recording start, including explicit timezone")@@ -169,34 +161,17 @@ def main():print(json.dumps(result[-1],indent=2))elif args.command=="discover":from .intake import intake_recording- overrides={name:getattr(args,name) for name in- ("min_frequency_hz","max_frequency_hz","window_s","hop_s")- if getattr(args,name) is not None}- if not args.experimental_episodes and (overrides or args.detailed_candidates):- parser.error("Frequency, window, hop and detailed-candidate options require --experimental-episodes")+ from .discovery import discover_eventsoutput=Path(args.output)try:- intake_options={}- discovery_options={}- if args.experimental_episodes:- from .episode_discovery import DiscoverySettings, discover_events, required_sample_rate- settings=DiscoverySettings(**overrides)- intake_options={"sample_rate_hz":required_sample_rate(settings),"resample_filter_size":64}- discovery_options={"settings":settings,"detailed_candidates":args.detailed_candidates}- else:- from .discovery import discover_eventsoutput.mkdir(parents=True,exist_ok=False)- recording=intake_recording(args.audio,output/"intake",**intake_options)+ recording=intake_recording(args.audio,output/"intake")events=discover_events(recording,output_dir=output/"discovery",- plot_summary=args.plot_summary,plot_event_details=args.plot_event_details,- **discovery_options)+ plot_summary=args.plot_summary,plot_event_details=args.plot_event_details)summary={"recording":recording.metadata,"time_status":recording.time_status,"events_found":len(events),"groups_found":len({event.get("harmonic_group_id") or event["event_id"] for event in events}),"scope":"Acoustic proposals only; aircraft identity and location are not established"}- if args.experimental_episodes:- summary.update(experimental_episodes=True,discovery_schema_version=2,- canonical_proposals=summary["groups_found"],measured_child_tracks=len(events))(output/"summary.json").write_text(json.dumps(summary,indent=2,allow_nan=False)+"\n")except (OSError, ValueError) as exc:parser.error(f"Could not complete discovery: {exc}")diff --git a/src/dopplergeist/discovery.py b/src/dopplergeist/discovery.pyindex 7fb352b..cab763a 100644--- a/src/dopplergeist/discovery.py+++ b/src/dopplergeist/discovery.py@@ -3,10 +3,11 @@Only decoded audio is read. Proposals are acoustic evidence, not proof of anaircraft identity. No straight-pass speed/slant fit is required for acceptance."""-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, replaceimport jsonfrom pathlib import Pathfrom statistics import median+from tempfile import TemporaryDirectoryimport numpy as npfrom scipy import ndimage, optimize, signal@@ -269,7 +270,7 @@ def _stitch_fragments(paths, settings, diagnostics=None):return result-def discover_events(recording, *, output_dir=None, settings=None, plot_summary=True, plot_event_details=False):+def _discover_baseline_events(recording, *, output_dir=None, settings=None, plot_summary=True, plot_event_details=False):"""Return shared DetectedEvent dictionaries from a disk-backed recording.Fixed defaults scan 40–1600 Hz in overlapping chunks; no event hints, flight@@ -349,6 +350,61 @@ def discover_events(recording, *, output_dir=None, settings=None, plot_summary=Treturn events+def discover_events(recording, *, output_dir=None, settings=None, plot_summary=True, plot_event_details=False):+ from .advanced_discovery import discover+ from .intake import intake_recording++ settings = settings or DiscoverySettings()+ if settings != DiscoverySettings():+ raise ValueError("Custom discovery settings are not supported")+ if recording.metadata["sample_rate_hz"] != 4000 or recording.source_path is None:+ raise ValueError("Discovery requires a 4000 Hz intake recording with its original audio source")++ def run(output):+ output.mkdir(parents=True, exist_ok=True)+ if (output / "discovery.json").exists():+ raise FileExistsError("Discovery output exists; use a new output directory")+ auxiliary = intake_recording(recording.source_path, output / "intake_high", sample_rate_hz=24000)+ if auxiliary.metadata["source_sha256"] != recording.metadata["source_sha256"]:+ raise ValueError("Audio source changed between intake and discovery")+ result = discover(recording, output, "ridge_dp_accel_broad_final_v25", aux_recording=auxiliary)+ tracks = {event["event_id"]: event for event in result["raw_events"]}+ tracks.update({event["event_id"]: event for event in result["verified_tracks"]})+ events, groups = [], []+ for proposal in result["events"]:+ group = []+ for event_id in proposal["raw_event_ids"]:+ track = tracks[event_id]+ event = {key: track[key] for key in ("event_id", "start_s", "end_s", "band_hz", "ridge", "quality") if key in track}+ event["harmonic_group_id"] = proposal["event_id"]+ frequencies = [point["frequency_hz"] for point in event["ridge"]]+ event["band_hz"] = [min(event["band_hz"][0], min(frequencies)), max(event["band_hz"][1], max(frequencies))]+ events.append(validate_event(event))+ group.append(np.array([[p["time_s"], p["frequency_hz"], p["weight"]] for p in event["ridge"]]))+ groups.append(group)+ if output_dir is not None:+ baseline_diagnostics = json.loads((output / "baseline-tracks/discovery.json").read_text())+ (output / "discovery.json").write_text(json.dumps({"source_sha256": recording.metadata["source_sha256"],+ "settings": asdict(settings), "sequence_settings": result["sequence_settings"],+ "events": events, "proposals": result["events"], "chunks": baseline_diagnostics["chunks"],+ "fragment_links": baseline_diagnostics["fragment_links"],+ "harmonic_ridges": [[points.tolist() for points in group] for group in groups],+ "scope": "automatic acoustic proposals; aircraft identity unconfirmed"}, indent=2, allow_nan=False) + "\n")+ if plot_summary:+ _plot_groups(groups, output / "discovery.png", recording.metadata["duration_s"], settings.max_gap_s)+ if plot_event_details:+ plot_settings = replace(settings, max_frequency_hz=8000.)+ for event in events:+ points = np.array([[p["time_s"], p["frequency_hz"], p["weight"]] for p in event["ridge"]])+ _plot_event(auxiliary, [points], event, plot_settings, output / f"{event['event_id']}.png")+ return events++ if output_dir is not None:+ return run(Path(output_dir))+ with TemporaryDirectory(prefix="doppler-discovery-") as temporary:+ return run(Path(temporary))++def _plot_groups(groups, path, duration, max_gap_s=2.0):import matplotlibmatplotlib.use("Agg")diff --git a/src/dopplergeist/intake.py b/src/dopplergeist/intake.pyindex 952c767..2acac78 100644--- a/src/dopplergeist/intake.py+++ b/src/dopplergeist/intake.py@@ -73,6 +73,7 @@ class IntakeRecording:samples_path: Pathmetadata: dictdiagnostics: dict+ source_path: Path | None = None@propertydef time_status(self):@@ -192,7 +193,7 @@ def intake_recording(source, output_dir, *, time_window=None, sample_rate_hz=400target.write(json.dumps(metadata, indent=2, allow_nan=False) + "\n")with (output / "intake.json").open("x") as target:target.write(json.dumps(diagnostics, indent=2, allow_nan=False) + "\n")- return IntakeRecording(samples_path, metadata, diagnostics)+ return IntakeRecording(samples_path, metadata, diagnostics, source)finally:if temporary is not None:temporary.unlink(missing_ok=True)diff --git a/tests/test_real_episode_cli.py b/tests/test_real_episode_cli.pyindex bb0b19d..6345577 100644--- a/tests/test_real_episode_cli.py+++ b/tests/test_real_episode_cli.py@@ -29,53 +29,28 @@ class RealEpisodeCli(unittest.TestCase):self.assertEqual(len(raw), excerpt["sample_count"] * 4)audio = root / f"recorded-excerpt-{index}.wav"wavfile.write(audio, fixture["sample_rate_hz"], np.frombuffer(raw, dtype="<f4"))- for experimental in (False, True):- output = root / f"scan-{index}-{experimental}"- command = [sys.executable, "-m", "dopplergeist.cli", "discover", str(audio),- "--output", str(output)]- if experimental:- command.append("--experimental-episodes")- process = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, timeout=60)- self.assertEqual(process.returncode, 0, process.stderr)- summary = json.loads(process.stdout)- artifact = json.loads((output / "discovery/discovery.json").read_text())- intake = json.loads((output / "intake/intake.json").read_text())- self.assertEqual(intake["sample_count"], excerpt["sample_count"])- self.assertEqual(summary["recording"]["duration_s"],- excerpt["sample_count"] / fixture["sample_rate_hz"])- self.assertEqual(summary["events_found"], len(artifact["events"]))- if experimental:- self.assertTrue(summary["experimental_episodes"])- self.assertEqual(artifact["schema_version"], 2)- self.assertEqual(artifact["status"], "complete")- self.assertEqual(summary["canonical_proposals"], len(artifact["episodes"]))- self.assertIn("filter_size=64", " ".join(intake["decode"]["command"]))- else:- self.assertNotIn("experimental_episodes", summary)- self.assertNotIn("episodes", artifact)- self.assertNotIn("aresample", " ".join(intake["decode"]["command"]))- self.assertEqual((output / "intake/recording.f32").read_bytes(), raw)-- refused = root / "unrequested-experimental-option"+ output = root / f"scan-{index}"+ command = [sys.executable, "-m", "dopplergeist.cli", "discover", str(audio),+ "--output", str(output)]+ process = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, timeout=120)+ self.assertEqual(process.returncode, 0, process.stderr)+ summary = json.loads(process.stdout)+ artifact = json.loads((output / "discovery/discovery.json").read_text())+ intake = json.loads((output / "intake/intake.json").read_text())+ self.assertEqual(intake["sample_count"], excerpt["sample_count"])+ self.assertEqual(summary["events_found"], len(artifact["events"]))+ self.assertEqual(summary["groups_found"], len(artifact["proposals"]))+ self.assertEqual((output / "intake/recording.f32").read_bytes(), raw)+ self.assertEqual(json.loads((output / "discovery/intake_high/recording.json").read_text())["sample_rate_hz"], 24000)++ refused = root / "removed-experimental-option"process = subprocess.run([sys.executable, "-m", "dopplergeist.cli", "discover", str(audio),- "--output", str(refused), "--max-frequency-hz", "6000"],+ "--output", str(refused), "--experimental-episodes"],cwd=ROOT, capture_output=True, text=True, timeout=60)self.assertEqual(process.returncode, 2)- self.assertIn("require --experimental-episodes", process.stderr)self.assertFalse(refused.exists())- unsupported = root / "unsupported-source-coverage"- process = subprocess.run(- [sys.executable, "-m", "dopplergeist.cli", "discover", str(audio),- "--output", str(unsupported), "--experimental-episodes", "--max-frequency-hz", "6000"],- cwd=ROOT, capture_output=True, text=True, timeout=60)- self.assertEqual(process.returncode, 2)- artifact = json.loads((unsupported / "discovery/discovery.json").read_text())- self.assertEqual(artifact["status"], "failed")- self.assertEqual(artifact["failure"]["code"], "unsupported_frequency_coverage")- self.assertFalse((unsupported / "summary.json").exists())-if __name__ == "__main__":unittest.main()