Skip to content

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

Stitch unique tonal fragments and expose observed gaps (#5)

Cinna Davis9b9dffa081b3
diff --git a/docs/AUDIO_DISCOVERY.md b/docs/AUDIO_DISCOVERY.md
index e7af900..9e2ab87 100644
--- a/docs/AUDIO_DISCOVERY.md
+++ b/docs/AUDIO_DISCOVERY.md
@@ -78,3 +78,20 @@ 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.
diff --git a/docs/HERMES_REFERENCE.md b/docs/HERMES_REFERENCE.md
new file mode 100644
index 0000000..c010359
--- /dev/null
+++ b/docs/HERMES_REFERENCE.md
@@ -0,0 +1,30 @@
+# Pinned Hermes comparison
+
+User-supplied reference: [mojomast/hermes-aircraft-doppler-geolocation](https://github.com/mojomast/hermes-aircraft-doppler-geolocation/tree/2c3ed20577bcce29058d73422dd4f85392d04c24),
+commit `2c3ed20577bcce29058d73422dd4f85392d04c24`, MIT license, Kyle Durepos.
+It is another independent implementation of the public video's method. No donor
+code was copied into our implementation in this comparison.
+
+The inspected scripts supply band/window-selected Viterbi ridge tracing, sub-bin
+measurement, multistart straight-pass fitting, explicit rejection diagnostics and
+emission-time candidate scoring. The README distinguishes real tone detection
+from its synthetic location self-test. It does not supply automatic event
+discovery, historical flight/terrain acquisition or national search. Its synthetic
+test supplies a single known flight and includes the true observer on its grid;
+that result cannot establish blind off-grid real localization. Its scorer's
+partial-overlap support is less strict than DOPPLERGEIST's full-event support.
+
+Our local comparison command was
+`/home/cinna/aircraft-audio-geolocation/.venv/bin/python -m pytest -q tests`
+in `/home/cinna/dopplergeist-reference-hermes`: **6 passed in 19.64 s**, including
+the donor's offline synthetic extraction/scoring test. This is a reference-code
+check, not DOPPLERGEIST automatic upload or national accuracy acceptance. The
+integration board records another worker's retained full donor replay; do not
+repeat it merely to duplicate green checks.
+
+A useful remaining audio experiment is a seeded dynamic-programming continuation
+for weak ridges, reusing our existing audio.trace_ridge. Any such fallback must
+select its own seeds/bands from the recording, reject unsupported noise paths,
+and be evaluated at fixed settings. A successful manual-band donor result is not
+evidence that this automatic step already works. Turning-flight fit rejection
+must not become a compulsory discovery gate.
diff --git a/src/aircraft_geoloc/discovery.py b/src/aircraft_geoloc/discovery.py
index 0a6a986..dea1f9d 100644
--- a/src/aircraft_geoloc/discovery.py
+++ b/src/aircraft_geoloc/discovery.py
@@ -30,6 +30,7 @@ class DiscoverySettings:
min_drop_hz: float = 4.0
min_fractional_drop: float = 0.03
max_gap_s: float = 2.0
+ max_fragment_gap_s: float = 20.0
max_peaks_per_frame: int = 60
def __post_init__(self):
@@ -139,6 +140,14 @@ def _overlap(a, b):
if last <= first:
return None
t = np.arange(first, last + 0.001, 0.5)
+ supported = np.ones(len(t), dtype=bool)
+ for path in (a, b):
+ following = np.clip(np.searchsorted(path[:, 0], t), 0, len(path) - 1)
+ previous = np.maximum(0, following - 1)
+ supported &= np.minimum(np.abs(t - path[following, 0]), np.abs(t - path[previous, 0])) <= 1.0
+ t = t[supported]
+ if len(t) < 3:
+ return None
return t, np.interp(t, a[:, 0], a[:, 1]), np.interp(t, b[:, 0], b[:, 1])
@@ -185,6 +194,59 @@ def _harmonic_groups(paths):
return sorted(groups, key=lambda group: group[0][0, 0])
+def _stitch_fragments(paths, settings, diagnostics=None):
+ """Join only reciprocal-unique, locally compatible tonal continuations.
+
+ Missing samples remain missing. A stitch is an acoustic hypothesis, not a
+ flight identity or an independent event. Competing continuations stay split.
+ """
+ paths = sorted(paths, key=lambda path: path[0, 0])
+ incoming = [[] for _ in paths]
+ outgoing = [[] for _ in paths]
+ for i, left in enumerate(paths):
+ tail = left[left[:, 0] >= left[-1, 0] - 6]
+ rate_left = -np.polyfit(tail[:, 0] - tail[0, 0], tail[:, 1], 1)[0]
+ for j in range(i + 1, len(paths)):
+ right = paths[j]
+ gap = right[0, 0] - left[-1, 0]
+ if gap <= 0 or gap > settings.max_fragment_gap_s:
+ continue
+ if gap / (right[-1, 0] - left[0, 0]) > 0.35:
+ continue
+ head = right[right[:, 0] <= right[0, 0] + 6]
+ rate_right = -np.polyfit(head[:, 0] - head[0, 0], head[:, 1], 1)[0]
+ drop = left[-1, 1] - right[0, 1]
+ rate = drop / gap
+ tolerance = max(2 / settings.window_s, 0.015 * left[-1, 1])
+ if min(rate_left, rate_right) <= 0.05 or drop < -tolerance or drop > left[-1, 1] * 0.3:
+ continue
+ if not 0.4 * min(rate_left, rate_right) - tolerance / gap <= rate <= 2.5 * max(rate_left, rate_right) + tolerance / gap:
+ continue
+ outgoing[i].append(j)
+ incoming[j].append(i)
+ following = {i: targets[0] for i, targets in enumerate(outgoing)
+ if len(targets) == 1 and len(incoming[targets[0]]) == 1}
+ if diagnostics is not None:
+ for i, targets in enumerate(outgoing):
+ for j in targets:
+ accepted = following.get(i) == j
+ diagnostics.append({"from_start_s": float(paths[i][0, 0]), "from_end_s": float(paths[i][-1, 0]),
+ "to_start_s": float(paths[j][0, 0]), "to_end_s": float(paths[j][-1, 0]),
+ "gap_s": float(paths[j][0, 0] - paths[i][-1, 0]), "accepted": accepted,
+ "reason": "reciprocal_unique_continuation" if accepted else "ambiguous_continuation"})
+ consumed, result = set(), []
+ for first in range(len(paths)):
+ if first in consumed:
+ continue
+ chain, current = [paths[first]], first
+ while current in following:
+ current = following[current]
+ chain.append(paths[current])
+ consumed.add(current)
+ result.append(np.concatenate(chain))
+ return result
+
+
def discover_events(recording, *, output_dir=None, settings=None):
"""Return shared DetectedEvent dictionaries from a disk-backed recording.
@@ -211,6 +273,8 @@ def discover_events(recording, *, output_dir=None, settings=None):
paths.extend(found)
chunks.append({"start_s": start, "duration_s": len(data) / sr, "usable_paths": len(found)})
paths = _merge_duplicates(paths)
+ fragment_links = []
+ paths = _stitch_fragments(paths, settings, fragment_links)
groups = _harmonic_groups(paths)
events = []
for index, group in enumerate(groups):
@@ -223,6 +287,7 @@ def discover_events(recording, *, output_dir=None, settings=None):
orders.add(min(_HARMONIC_RATIOS, key=lambda value: abs(value - ratio)))
margin = 2 / settings.window_s
smooth = ndimage.median_filter(f, size=5, mode="nearest")
+ frequency_scale = float(max(1 / settings.window_s, 1.4826 * np.median(np.abs(f - smooth))))
event = {"event_id": f"event-{index + 1:04d}", "harmonic_group_id": f"harmonics-{index + 1:04d}",
"start_s": max(0.0, float(t[0] - settings.window_s / 2)),
"end_s": min(recording.metadata["duration_s"], float(t[-1] + settings.window_s / 2)),
@@ -232,12 +297,16 @@ def discover_events(recording, *, output_dir=None, settings=None):
"support_fraction": min(1.0, len(t) / (np.ptp(t) / settings.hop_s + 1)),
"frequency_resolution_hz": 1 / settings.window_s,
"time_uncertainty_s": settings.window_s / 2,
- "frequency_uncertainty_hz": float(max(1 / settings.window_s, 1.4826 * np.median(np.abs(f - smooth)))),
+ "frequency_uncertainty_hz": frequency_scale,
+ "frequency_sigma_hz": frequency_scale,
+ "fragment_count": float(1 + np.sum(np.diff(t) > settings.max_gap_s)),
+ "max_observed_gap_s": float(np.max(np.diff(t))),
"frequency_drop_hz": float(np.median(f[:max(3, len(f) // 6)]) - np.median(f[-max(3, len(f) // 6):]))}}
events.append(validate_event(event))
if output:
diagnostics = {"source_sha256": recording.metadata["source_sha256"], "settings": asdict(settings),
"events": events, "chunks": chunks, "ridge_count": len(paths),
+ "fragment_links": fragment_links,
"harmonic_ridges": [[points.tolist() for points in group] for group in groups],
"scope": "automatic acoustic moving-tone proposals; aircraft identity unconfirmed"}
(output / "discovery.json").write_text(json.dumps(diagnostics, indent=2, allow_nan=False) + "\n")
diff --git a/tests/test_discovery.py b/tests/test_discovery.py
index 92b4246..adce337 100644
--- a/tests/test_discovery.py
+++ b/tests/test_discovery.py
@@ -2,11 +2,11 @@ import numpy as np
import soundfile as sf
from aircraft_geoloc.contracts import validate_event
-from aircraft_geoloc.discovery import discover_events
+from aircraft_geoloc.discovery import DiscoverySettings, _stitch_fragments, discover_events
from aircraft_geoloc.intake import intake_recording
-def _audio(tmp_path, events, duration=180):
+def _audio(tmp_path, events, duration=180, mute=None):
sr = 4000
t = np.arange(sr * duration) / sr
data = np.random.default_rng(9133).normal(0, 0.08, len(t))
@@ -16,6 +16,8 @@ def _audio(tmp_path, events, duration=180):
frequency = f0 * (1 - 0.18 * relative / np.sqrt(relative ** 2 + 8 ** 2))
phase = 2 * np.pi * np.cumsum(frequency) / sr
amplitude = 0.16 * np.exp(-(relative / 24) ** 2) * (np.abs(relative) < 44)
+ if mute is not None:
+ amplitude *= (t < mute[0]) | (t > mute[1])
for harmonic in harmonics:
data += amplitude / harmonic * np.sin(harmonic * phase)
path = tmp_path / "recording.wav"
@@ -79,3 +81,24 @@ def test_switching_stationary_tones_do_not_make_a_flyover(tmp_path):
path = tmp_path / "switching.wav"
sf.write(path, data, sr)
assert discover_events(intake_recording(path, tmp_path / "intake")) == []
+
+
+def test_interrupted_tone_is_one_event_without_invented_gap_observations(tmp_path):
+ recording = _audio(tmp_path, [(65, 120, [1, 2])], duration=140, mute=(58, 69))
+ events = discover_events(recording)
+ assert len(events) == 1
+ event = events[0]
+ assert event["quality"]["fragment_count"] >= 2
+ assert event["quality"]["max_observed_gap_s"] >= 7
+ assert not any(60 < point["time_s"] < 67 for point in event["ridge"])
+ assert event["quality"]["frequency_sigma_hz"] == event["quality"]["frequency_uncertainty_hz"]
+
+
+def test_ambiguous_fragment_continuations_remain_separate():
+ def path(start, end, offset=0):
+ t = np.arange(start, end, 0.5)
+ return np.column_stack((t, 180 - 0.7 * t + offset, np.full(len(t), 5)))
+ first, second, competitor = path(0, 24), path(30, 55), path(31, 56, 0.5)
+ assert len(_stitch_fragments([first, second, competitor], DiscoverySettings())) == 3
+ assert len(_stitch_fragments([first, second], DiscoverySettings())) == 1
+ assert len(_stitch_fragments([first, path(50, 80)], DiscoverySettings())) == 2