Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Preserve whole ADS-B traces in bounded ingestion
Cinna Davisd7b5976a5071
diff --git a/docs/HISTORICAL_INGESTION.md b/docs/HISTORICAL_INGESTION.mdindex c2e2a19..fd89482 100644--- a/docs/HISTORICAL_INGESTION.md+++ b/docs/HISTORICAL_INGESTION.md@@ -1,14 +1,16 @@# Historical derived-Parquet ingestion-`scripts/ingest_adsblol_day.py` keeps its existing geographic/time/type selection-and column schema. It first rejects aircraft with no requested raw points, then-normalizes each retained aircraft's **full native trace** before selecting output-rows. Geometric-minus-barometric calibration samples outside the selected box or-clock window remain available to the existing altitude normalizer. Output rows-still obey the requested bounds; the normalized full trace is not written.+`scripts/ingest_adsblol_day.py` normalizes each potentially relevant aircraft's+**full native trace**, then selects aircraft whose gap-split trajectory envelopes+intersect the requested geographic box and time window. It writes the whole+normalized trace for each selected aircraft, including rows outside those bounds.+This preserves altitude calibration, segment boundary derivatives and passages+that cross a query between recorded samples. The conservative continuous bounds+and 30-second gap limit match the default `FlightIndex` build; a differently+configured gap limit requires a new selection. The report records that limit.The ingestion report records-`normalization_scope: full_native_trace_before_row_selection`. Existing output or+`normalization_scope: full_native_trace_before_segment_selection`. Existing output orreport paths raise `FileExistsError`; use a new `--output` name. HistoricalParquet files, indexes and scientific results are not rewritten by this repair.The normalizer's interpolation, missingness and altitude labels are unchanged.@@ -18,10 +20,12 @@ trace. Geometric observations lie outside the selected time window, geographicbox, or both. Two retained barometric observations have an independently specified450 ft / 137.16 m calibration offset: old ingestion loses it and produces 1524 m;the corrected script produces 1661.16 m with `ellipsoidal_interpolated` labels.-The test checks retained rows, source hashes and refusal to overwrite the result.+The existing software test checks full-trace retention, altitude labels, source+hashes and refusal to overwrite the result.No network access or recorder coordinates enter this control.-This repairs the historical script boundary identified by the #64 audit. The-automatic `FlightCache` already normalizes full native traces; this increment+Older derived Parquet files used pointwise clipping and cannot be assumed to+contain complete segments. Regenerate them before claiming complete query+coverage. The automatic `FlightCache` already normalizes full native traces; this incrementdoes not change its normalizer/index format, certify bad motion intervals,establish terrain/altitude datum uncertainty or close the complete #64 gate.diff --git a/scripts/ingest_adsblol_day.py b/scripts/ingest_adsblol_day.pyindex 20b0a4c..b9277c3 100644--- a/scripts/ingest_adsblol_day.py+++ b/scripts/ingest_adsblol_day.py@@ -13,6 +13,7 @@ import pyarrow.parquet as pqimport requestsfrom dopplergeist.tracks import adsblol_frame,unix_time+from dopplergeist.flight_selection import intersects_index_queryparser=argparse.ArgumentParser()parser.add_argument("date")@@ -68,7 +69,8 @@ class SplitReader(io.RawIOBase):paths=sorted(directory.glob("*.tar.a?"))if len(paths)<2:raise ValueError("Daily archive download is incomplete")stats={"trace_files":0,"known_jets_removed":0,"no_conus_points":0,"retained_aircraft":0,"rows":0,"barometric_rows":0}-stats["normalization_scope"]="full_native_trace_before_row_selection"+stats["normalization_scope"]="full_native_trace_before_segment_selection"+stats["selection_max_gap_s"]=30.0writer=Nonewith io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream:with tarfile.open(fileobj=stream,mode="r|") as archive:@@ -80,20 +82,20 @@ with io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream: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 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"]+=1- continue- # The cheap raw selection above can reject an irrelevant aircraft,- # but altitude calibration needs this aircraft's full native trace.- frame=adsblol_frame(d)- if frame.empty:continue- keep=frame.lat.between(south,north)&frame.lon.between(west,east)+ # A segment can cross a query without a sample inside it. Temporal+ # extents can reject only traces entirely before or after the query.if time_range is not None:- keep&=frame.time_s.between(*time_range)- frame=frame.loc[keep].copy()+ offsets=[p[0] for p in d.get("trace",[]) if isinstance(p[0],(int,float)) and np.isfinite(p[0])]+ if not offsets or d["timestamp"]+min(offsets)>time_range[1] or d["timestamp"]+max(offsets)<time_range[0]:+ stats["no_conus_points"]+=1+ continue+ frame=adsblol_frame(d)if frame.empty:continue+ if not intersects_index_query(frame,(west,south,east,north),time_range):+ stats["no_conus_points"]+=1+ continue+ # Keep the native trace intact: FlightIndex performs its own+ # gap splitting and uses neighboring samples to infer velocity.frame["heading_deg"]=frame.heading_deg.astype(float)# Bound schema explicitly so an all-null metadata field in one# aircraft cannot change a later parquet batch's physical type.diff --git a/src/dopplergeist/flight_selection.py b/src/dopplergeist/flight_selection.pynew file mode 100644index 0000000..e11ae09--- /dev/null+++ b/src/dopplergeist/flight_selection.py@@ -0,0 +1,42 @@+"""Select native traces without clipping the trajectories used by the index."""++import json++import numpy as np+import pandas as pd++from .data_access import _continuous_bounds, _frame_track+++def intersects_index_query(frame, bounds, time_range, *, max_gap_s=30.0):+ """Whether any indexable segment's conservative envelope meets a query.++ The input must be the complete normalized trace. Match FlightIndex's valid+ row filtering, serialization precision, gap splitting and continuous bounds.+ The caller retains the *entire* original frame on a match, since trimming+ changes boundary derivatives and can create artificial track endpoints.+ """+ if frame.empty:+ return False+ valid = np.isfinite(frame[["time_s", "lat", "lon", "alt_m"]].to_numpy(dtype=float)).all(axis=1)+ valid &= frame.lat.between(-90, 90) & frame.lon.between(-180, 180) & frame.flight_id.notna()+ clean = frame.loc[valid]+ if clean.empty:+ return False+ # FlightIndex writes through JSON before deriving segment geometry.+ clean = pd.DataFrame(json.loads(clean.to_json(orient="records", double_precision=15)))+ west, south, east, north = bounds+ for flight, rows in clean.groupby("flight_id", sort=False):+ rows = rows.sort_values("time_s", kind="stable").drop_duplicates("time_s")+ groups = (rows.time_s.diff() > max_gap_s).cumsum()+ for _, chunk in rows.groupby(groups):+ if len(chunk) < 3:+ continue+ if time_range is not None and (chunk.time_s.iloc[0] > time_range[1] or+ chunk.time_s.iloc[-1] < time_range[0]):+ continue+ track = _frame_track(str(flight), chunk)+ seg_west, seg_east, seg_south, seg_north = _continuous_bounds(track)+ if seg_west <= east and seg_east >= west and seg_south <= north and seg_north >= south:+ return True+ return Falsediff --git a/tests/test_ingest_adsblol_day.py b/tests/test_ingest_adsblol_day.pyindex 0d46e52..b4c24f8 100644--- a/tests/test_ingest_adsblol_day.py+++ b/tests/test_ingest_adsblol_day.py@@ -51,12 +51,14 @@ def test_native_altitude_support_is_normalized_before_row_selection(tmp_path, seresult = subprocess.run(command, cwd=project, env=env, capture_output=True, text=True)assert result.returncode == 0, result.stderrrows = pd.read_parquet(day / "new.parquet")- assert rows.time_s.tolist() == [1790000010, 1790000020]- assert rows.alt_m.tolist() == pytest.approx([5450 * 0.3048] * 2)- assert rows.altitude_basis.tolist() == ["ellipsoidal_interpolated"] * 2+ assert rows.time_s.tolist() == [1790000000, 1790000010, 1790000020, 1790000030]+ assert rows.alt_m.tolist() == pytest.approx([5450 * 0.3048] * 4)+ assert rows.altitude_basis.tolist() == ["ellipsoidal", "ellipsoidal_interpolated",+ "ellipsoidal_interpolated", "ellipsoidal"]report = json.loads((day / "new-ingestion-report.json").read_text())assert report["barometric_rows"] == 0- assert report["normalization_scope"] == "full_native_trace_before_row_selection"+ assert report["normalization_scope"] == "full_native_trace_before_segment_selection"+ assert report["selection_max_gap_s"] == 30.0assert all(hashlib.sha256((day / n).read_bytes()).hexdigest() == h for n, h in original.items())# Repeating an old output name must preserve its historical bytes.artifact = (day / "new.parquet").read_bytes()diff --git a/tests/test_real_flight_selection.py b/tests/test_real_flight_selection.pynew file mode 100644index 0000000..8b16628--- /dev/null+++ b/tests/test_real_flight_selection.py@@ -0,0 +1,58 @@+"""Optional integration regression against a local, real ADS-B archive part."""+import gzip+import json+import os+from pathlib import Path+import tarfile++import numpy as np+import pytest++from dopplergeist.data_access import FlightIndex+from dopplergeist.flight_selection import intersects_index_query+from dopplergeist.tracks import adsblol_frame+++def test_real_boundary_segments_survive_selection(tmp_path):+ source = os.environ.get("DOPPLERGEIST_REAL_ARCHIVE_PART")+ if not source:+ pytest.skip("set DOPPLERGEIST_REAL_ARCHIVE_PART to a local readsb tar part")+ frames = []+ with Path(source).open("rb") as stream, tarfile.open(fileobj=stream, mode="r|") as archive:+ for member in archive:+ if not member.isfile() or "trace_full_" not in member.name:+ continue+ raw = archive.extractfile(member).read()+ data = json.loads(gzip.decompress(raw) if raw[:2] == b"\x1f\x8b" else raw)+ frame = adsblol_frame(data)+ if len(frame) > 50:+ frames.append(frame)+ if len(frames) == 10:+ break+ assert len(frames) == 10+ bounds = (-180, -90, 180, 90)+ coverage = {"bounds": list(bounds), "time_range_s": [0, 4102444800],+ "all_aircraft": True, "release_tag": "real-regression"}+ full = FlightIndex.build(tmp_path / "full.sqlite", frames, sources=[], coverage=coverage)+ checked = old_filter_misses = 0+ for frame in frames:+ rows = frame.dropna(subset=["time_s", "lat", "lon", "alt_m"]).sort_values("time_s").drop_duplicates("time_s")+ gaps = np.diff(rows.time_s.to_numpy())+ choices = np.flatnonzero((gaps > 0.02) & (gaps <= 30))+ if not len(choices):+ continue+ i = int(choices[len(choices) // 2])+ a, b = float(rows.time_s.iloc[i]), float(rows.time_s.iloc[i + 1])+ interval = (a + (b - a) * 0.4, a + (b - a) * 0.6)+ selected_ids = {str(f.flight_id.iloc[0]) for f in frames+ if intersects_index_query(f, bounds, interval)}+ matches = list(full.query(bounds, interval))+ assert all(track.id.split("@")[0] in selected_ids for track in matches)+ own_id = str(frame.flight_id.iloc[0])+ if any(track.id.split("@")[0] == own_id for track in matches):+ old_filter_misses += not frame.time_s.between(*interval).any()+ checked += 1+ if checked == 5:+ break+ assert checked == 5+ assert old_filter_misses > 0