Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Normalize complete native traces before historical row selection (#64)
Cinna Davis0b74efa88b94
diff --git a/docs/HISTORICAL_INGESTION.md b/docs/HISTORICAL_INGESTION.mdnew file mode 100644index 0000000..c2e2a19--- /dev/null+++ b/docs/HISTORICAL_INGESTION.md@@ -0,0 +1,27 @@+# 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.++The ingestion report records+`normalization_scope: full_native_trace_before_row_selection`. Existing output or+report paths raise `FileExistsError`; use a new `--output` name. Historical+Parquet files, indexes and scientific results are not rewritten by this repair.+The normalizer's interpolation, missingness and altitude labels are unchanged.++The actual-script regression streams a two-part tar containing a gzip readsb+trace. Geometric observations lie outside the selected time window, geographic+box, or both. Two retained barometric observations have an independently specified+450 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.+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+does 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 5b5ba75..08e093d 100644--- a/scripts/ingest_adsblol_day.py+++ b/scripts/ingest_adsblol_day.py@@ -25,6 +25,10 @@ root=Path(__file__).resolve().parents[1]directory=root/"data/adsb"/args.datewest,south,east,north=args.boundstime_range=[unix_time(t) for t in args.time_range] if args.time_range else None+output_path=directory/args.output+report_path=directory/(Path(args.output).stem+"-ingestion-report.json")+if output_path.exists() or report_path.exists():+ raise FileExistsError("Ingestion output exists; choose a new --output name to preserve historical evidence")types_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)@@ -64,6 +68,7 @@ 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"writer=Nonewith io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream:with tarfile.open(fileobj=stream,mode="r|") as archive:@@ -80,19 +85,25 @@ with io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream:if not trace:stats["no_conus_points"]+=1continue- d["trace"]=trace+ # 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)+ if time_range is not None:+ keep&=frame.time_s.between(*time_range)+ frame=frame.loc[keep].copy()+ if frame.empty:continueframe["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.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/args.output,schema,compression="zstd")+ if writer is None:writer=pq.ParquetWriter(output_path,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/(Path(args.output).stem+"-ingestion-report.json")).write_text(json.dumps(stats,indent=2)+"\n")+report_path.write_text(json.dumps(stats,indent=2)+"\n")print(stats,flush=True)diff --git a/tests/test_ingest_adsblol_day.py b/tests/test_ingest_adsblol_day.pynew file mode 100644index 0000000..0d46e52--- /dev/null+++ b/tests/test_ingest_adsblol_day.py@@ -0,0 +1,65 @@+"""Exercise the actual historical CLI with calibration outside selection bounds."""+import gzip+import hashlib+import io+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tarfile++import pandas as pd+import pytest++[email protected]("selection", ["time", "space", "both"])+def test_native_altitude_support_is_normalized_before_row_selection(tmp_path, selection):+ root = Path(__file__).resolve().parents[1]+ project = tmp_path / "isolated-project"+ scripts = project / "scripts"+ scripts.mkdir(parents=True)+ script = scripts / "ingest_adsblol_day.py"+ shutil.copyfile(root / "scripts/ingest_adsblol_day.py", script)+ source = project / "data/source"+ source.mkdir(parents=True)+ (source / "icao_aircraft_types.json").write_text('{}')+ day = project / "data/adsb/2026-09-22"+ day.mkdir(parents=True)+ trace = {"icao": "opaque-flight", "timestamp": 1790000000, "t": "PC12", "trace": [+ [t, lat, -100, 5000, 100, 90, 0, 0, {}, 0, geometric, None]+ for t, lat, geometric in [(0, 40.2, 5450), (10, 40.05, None),+ (20, 40.05, None), (30, 40.2, 5450)]]}+ member = gzip.compress(json.dumps(trace).encode())+ archive = io.BytesIO()+ with tarfile.open(fileobj=archive, mode="w") as output:+ info = tarfile.TarInfo("traces/trace_full_opaque-flight.json")+ info.size = len(member)+ output.addfile(info, io.BytesIO(member))+ raw = archive.getvalue()+ for name, part in [("archive.tar.aa", raw[:len(raw)//2]), ("archive.tar.ab", raw[len(raw)//2:])]:+ (day / name).write_bytes(part)+ original = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in day.iterdir()}+ bounds = [-101, 40, -99, 40.1 if selection != "time" else 40.3]+ command = [sys.executable, str(script), "2026-09-22", "--output", "new.parquet",+ "--bounds", *map(str, bounds)]+ if selection != "space":+ command += ["--time-range", *[pd.Timestamp(t, unit="s", tz="UTC").isoformat()+ for t in (1790000010, 1790000020)]]+ env = dict(os.environ, PYTHONPATH=str(root / "src"))+ result = subprocess.run(command, cwd=project, env=env, capture_output=True, text=True)+ assert result.returncode == 0, result.stderr+ rows = 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+ 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 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()+ repeated = subprocess.run(command, cwd=project, env=env, capture_output=True, text=True)+ assert repeated.returncode != 0 and "FileExistsError" in repeated.stderr+ assert (day / "new.parquet").read_bytes() == artifact