Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Retain measured harmonics in automatic matching
Cinna Davisc8e120c25efa
diff --git a/src/dopplergeist/discovery.py b/src/dopplergeist/discovery.pyindex 7ca73e8..70aca19 100644--- a/src/dopplergeist/discovery.py+++ b/src/dopplergeist/discovery.py@@ -251,7 +251,8 @@ def discover_events(recording, *, output_dir=None, settings=None):"""Return shared DetectedEvent dictionaries from a disk-backed recording.Fixed defaults scan 40–1600 Hz in overlapping chunks; no event hints, flight- data or truth paths are accepted. Harmonics become one independent event.+ data or truth paths are accepted. Each measured ridge gets a record; a+ shared harmonic_group_id makes those records one independent proposal.Optional diagnostics retain all measured harmonic ridges and chunk counts."""settings = settings or DiscoverySettings()@@ -276,19 +277,22 @@ def discover_events(recording, *, output_dir=None, settings=None):fragment_links = []paths = _stitch_fragments(paths, settings, fragment_links)groups = _harmonic_groups(paths)- events = []+ events, event_groups = [], []for index, group in enumerate(groups):- points = group[0]- t, f, weight = points.Torders = {1.0}for harmonic in group[1:]:- _, base_f, harmonic_f = _overlap(points, harmonic)+ _, base_f, harmonic_f = _overlap(group[0], harmonic)ratio = np.median(harmonic_f / base_f)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}",+ for harmonic_index, points in enumerate(group):+ t, f, weight = points.T+ 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_id = f"event-{index + 1:04d}"+ if harmonic_index:+ event_id += f"-harmonic-{harmonic_index + 1}"+ event = {"event_id": event_id, "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)),"band_hz": [max(0.01, float(f.min() - margin)), float(f.max() + margin)],@@ -302,7 +306,8 @@ def discover_events(recording, *, output_dir=None, settings=None):"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))+ events.append(validate_event(event))+ event_groups.append(group)if output:diagnostics = {"source_sha256": recording.metadata["source_sha256"], "settings": asdict(settings),"events": events, "chunks": chunks, "ridge_count": len(paths),@@ -311,8 +316,9 @@ def discover_events(recording, *, output_dir=None, settings=None):"scope": "automatic acoustic moving-tone proposals; aircraft identity unconfirmed"}(output / "discovery.json").write_text(json.dumps(diagnostics, indent=2, allow_nan=False) + "\n")_plot_groups(groups, output / "discovery.png", recording.metadata["duration_s"], settings.max_gap_s)- for event, group in zip(events, groups):- np.savetxt(output / f"{event['event_id']}.csv", group[0], delimiter=",",+ for event, group in zip(events, event_groups):+ points = np.array([[p["time_s"], p["frequency_hz"], p["weight"]] for p in event["ridge"]])+ np.savetxt(output / f"{event['event_id']}.csv", points, delimiter=",",header="time_s,frequency_hz,weight", comments="")_plot_event(recording, group, event, settings, output / f"{event['event_id']}.png")return eventsdiff --git a/src/dopplergeist/matching.py b/src/dopplergeist/matching.pyindex a1c685b..5c4b5e2 100644--- a/src/dopplergeist/matching.py+++ b/src/dopplergeist/matching.py@@ -255,12 +255,14 @@ def association_score(result, events):def prepare_events(detected_events, c=343.0, max_distance_m=20000.0):"""Adapt contract ridge points to existing search inputs without truth hints.- Keep every ridge in a harmonic group as evidence for one pass. Integer- harmonics are normalized to its lowest observed band; no fundamental needs- to be present. Groups with inconsistent ratios must be fixed by discovery.+ Keep every ridge in a harmonic group as evidence for one pass. Rational+ harmonic ratios are normalized to its lowest observed band; no fundamental+ needs to be present. Groups with inconsistent ratios must be fixed by discovery.Timing uncertainty spans the observed window, because a curved track neednot have its geometric CPA at a fitted straight-pass center."""+ from .discovery import _HARMONIC_RATIOS, _overlap+groups = {}for event in detected_events:key = event.get("harmonic_group_id") or event["event_id"]@@ -275,13 +277,16 @@ def prepare_events(detected_events, c=343.0, max_distance_m=20000.0):t = np.array([p["time_s"] for p in member["ridge"]], dtype=float)f = np.array([p["frequency_hz"] for p in member["ridge"]], dtype=float)w = np.array([p.get("weight", 1.0) for p in member["ridge"]], dtype=float)- overlapping = (t >= reference_time[0]) & (t <= reference_time[-1])- if not overlapping.any():- raise ValueError("Harmonic-group ridges must overlap in recording time")- ratio = np.median(f[overlapping] / np.interp(t[overlapping], reference_time, reference_frequency))- harmonic = max(1, round(ratio))- if abs(ratio / harmonic - 1) > 0.05:- raise ValueError("Harmonic group does not have consistent integer frequency ratios")+ harmonic = 1.0+ if member is not reference:+ base = np.column_stack((reference_time, reference_frequency))+ shared = _overlap(base, np.column_stack((t, f)))+ if shared is None or len(shared[0]) * 0.5 < 0.6 * min(np.ptp(reference_time), np.ptp(t)):+ raise ValueError("Harmonic-group ridges lack sufficient shared observations")+ ratio = shared[2] / shared[1]+ harmonic = min([1.0, *_HARMONIC_RATIOS], key=lambda value: abs(value - np.median(ratio)))+ if np.quantile(np.abs(ratio - harmonic) / harmonic, 0.9) >= 0.008:+ raise ValueError("Harmonic group does not have a consistent supported frequency ratio")times.extend(t)frequencies.extend(f / harmonic)# Equal aggregate weight per ridge prevents duplicated harmonicsdiff --git a/tests/test_discovery.py b/tests/test_discovery.pyindex 83a2b47..f075a2b 100644--- a/tests/test_discovery.py+++ b/tests/test_discovery.py@@ -5,6 +5,11 @@ import soundfile as sffrom dopplergeist.contracts import validate_eventfrom dopplergeist.discovery import DiscoverySettings, _stitch_fragments, discover_eventsfrom dopplergeist.intake import intake_recording+from dopplergeist.matching import prepare_events+++def _groups(events):+ return list(dict.fromkeys(event["harmonic_group_id"] for event in events))def _audio(tmp_path, events, duration=180, mute=None):@@ -29,10 +34,13 @@ def _audio(tmp_path, events, duration=180, mute=None):def test_blind_whole_file_seams_harmonics_and_separate_events(tmp_path):recording = _audio(tmp_path, [(65, 120, [1, 2, 3]), (135, 250, [1, 2])])events = discover_events(recording, output_dir=tmp_path / "discovery")- assert len(events) == 2, [(e["start_s"], e["end_s"], e["band_hz"]) for e in events]- for center, event in zip((65, 135), events):+ groups = _groups(events)+ assert len(groups) == 2, [(e["start_s"], e["end_s"], e["band_hz"]) for e in events]+ for center, group in zip((65, 135), groups):+ event = next(e for e in events if e["harmonic_group_id"] == group)assert event["start_s"] < center < event["end_s"]assert event["quality"]["harmonic_count"] >= 2+ for event in events:assert validate_event(event) == eventassert np.all(np.diff([point["time_s"] for point in event["ridge"]]) > 0)assert (tmp_path / "discovery" / "discovery.png").is_file()@@ -57,8 +65,10 @@ def signal_chirp(t):def test_overlapping_nonharmonic_events_are_retained(tmp_path):recording = _audio(tmp_path, [(60, 120, [1, 2]), (76, 210, [1])], duration=140)events = discover_events(recording)- assert len(events) == 2, [(e["start_s"], e["end_s"], e["band_hz"]) for e in events]- assert events[0]["end_s"] > events[1]["start_s"]+ groups = _groups(events)+ assert len(groups) == 2, [(e["start_s"], e["end_s"], e["band_hz"]) for e in events]+ first, second = (next(e for e in events if e["harmonic_group_id"] == group) for group in groups)+ assert first["end_s"] > second["start_s"]def test_short_input_has_no_forced_event(tmp_path):@@ -69,8 +79,12 @@ def test_short_input_has_no_forced_event(tmp_path):def test_missing_fundamental_harmonics_are_one_event(tmp_path):recording = _audio(tmp_path, [(65, 120, [2, 3])], duration=140)events = discover_events(recording)- assert len(events) == 1+ assert len(_groups(events)) == 1assert events[0]["quality"]["harmonic_count"] == 2+ assert len(events) == 2+ prepared, measurements = prepare_events(events)+ assert len(prepared) == 1+ assert len(measurements[0][1]) == sum(len(event["ridge"]) for event in events)def test_switching_stationary_tones_do_not_make_a_flyover(tmp_path):@@ -87,7 +101,7 @@ def test_switching_stationary_tones_do_not_make_a_flyover(tmp_path):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+ assert len(_groups(events)) == 1event = events[0]assert event["quality"]["fragment_count"] >= 2assert event["quality"]["max_observed_gap_s"] >= 7@@ -113,7 +127,9 @@ def test_all_independent_flyovers_are_retained(tmp_path, count):for center, frequency in zip(centers, frequencies)],duration=100 * count + 30)events = discover_events(recording)- assert len(events) == count- for center, event in zip(centers, events):+ groups = _groups(events)+ assert len(groups) == count+ for center, group in zip(centers, groups):+ event = next(e for e in events if e["harmonic_group_id"] == group)assert event["start_s"] < center < event["end_s"]assert event["quality"]["harmonic_count"] >= 2diff --git a/tests/test_matching.py b/tests/test_matching.pyindex 3a27a1a..bab299a 100644--- a/tests/test_matching.py+++ b/tests/test_matching.py@@ -104,8 +104,8 @@ def test_adapter_retains_jet_with_misleading_straight_geometry_and_merges_harmonassert abs(one["score"] - two["score"]) < 1e-8inconsistent = detected("bad", 2)for p in inconsistent["ridge"]:- p["frequency_hz"] *= 0.75- with pytest.raises(ValueError, match="integer"):+ p["frequency_hz"] *= 0.73+ with pytest.raises(ValueError, match="supported frequency ratio"):prepare_events([detected(), inconsistent])