Skip to content

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

Implement aircraft acoustic geolocation pipeline and independent synthetic validation

Cinna Davis54b1cb44e0e6
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8ea41c9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+.venv/
+__pycache__/
+*.egg-info/
+.pytest_cache/
+data/
+results/
+!data/.gitkeep
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..3d982cc
--- /dev/null
+++ b/README.md
@@ -0,0 +1,76 @@
+# Aircraft-acoustic geolocation reproduction
+
+This project reconstructs the method in [colsto's video](https://www.youtube.com/watch?v=UytYrhYLOKI):
+measure aircraft Doppler curves, constrain flight geometry, account for sound travel
+time and terrain, and score candidate recording positions against actual ADS-B tracks.
+
+**Status:** the complete local pipeline is implemented. Independent synthetic
+audio-to-location runs recover the correct flights with 21.9 m error for two events
+with unknown recording start, and 40.9 m error for a known-time one-minute event.
+Real-world location verification is in progress; these synthetic errors do not
+establish the video's real-world or national-search claims.
+
+## Run
+
+Python 3.11+ and `ffmpeg` are required. The current local environment is `.venv/`.
+
+```bash
+python -m venv .venv
+.venv/bin/pip install -e . pytest
+.venv/bin/python -m pytest -q
+.venv/bin/python scripts/make_synthetic_cases.py
+.venv/bin/aircraft-geoloc run data/synthetic/two-events.json --output results/two-events
+.venv/bin/aircraft-geoloc run data/synthetic/known-time-minute.json --output results/known-minute
+```
+
+The generator writes truth separately. The search never loads it. Its audio
+renderer transports an oscillator from emission time into receiver time without
+calling the search's propagation model. Three widely separated regions contain
+plausible flights; a known jet tests classification. Results include a ranked list
+of points, the best point per flight combination, measured spectra, physical-model
+overlays, filter counts, input hashes, and timings.
+
+## Inputs and physical model
+
+A JSON configuration identifies an audio/video file, flight-data files, event
+windows/bands, terrain, a projected grid, filter tolerances and scoring settings.
+Event speed, slant-distance and rest-frequency ranges may be set explicitly or
+estimated from the measured curve. The video likewise uses manual event selection
+and generous geometry bounds; fully unattended event discovery is not assumed.
+
+Canonical CSV/Parquet columns are `flight_id,time_s,lat,lon,alt_m,typecode`.
+Timestamps are Unix seconds or UTC ISO strings; heights and speeds are SI units.
+Optional `east_mps,north_mps,up_mps` supply actual flight velocity. KML gx:Track
+and readsb/ADSB.lol traces have importers. Gaps are split instead of interpolated
+through. Unknown aircraft types are retained; only positively identified jet types
+are removed. Readsb geometric-altitude fields and barometric fallbacks are labelled.
+
+For aircraft position **x** at emission time tau and observer **o**, the code solves
+
+```
+t_received = tau + norm(x(tau) - o) / c
+frequency = f0 * c / (c + dot(velocity(tau), x(tau)-o)/norm(x(tau)-o))
+```
+
+Range rate is positive for a receding aircraft. A shared recording-clock adjustment
+is fitted across all events; each event can adjust its rest frequency, but a second
+event cannot shift independently in time. Scoring uses either normalized spectral
+brightness along the predicted curves or residual against a measured ridge.
+
+DEM rasters are sampled in their actual CRS. An optional geoid raster converts
+orthometric ground height to the ellipsoidal datum used by GNSS aircraft heights.
+Without a geoid, both aircraft and observer must use one common height datum.
+Constant terrain is available for explicit controlled tests, not an implied DEM.
+
+## Evidence and next work
+
+- [Current checkpoint](docs/PROGRESS.md)
+- Source video captions, metadata, source frames and audio: `data/source/`
+- Real paired research data: `scripts/fetch_research_data.py`
+- Open historical ADS-B data: `scripts/fetch_adsblol_day.py YYYY-MM-DD`, then
+ `scripts/ingest_adsblol_day.py YYYY-MM-DD`
+- Local reports: `results/synthetic-two-events/` and `results/synthetic-known-minute/`
+
+External recordings and large datasets stay outside Git. Downloaded research data
+is checksum verified. The first real reproduction uses an area identified in the
+video to validate data alignment before attempting a blind national search.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
new file mode 100644
index 0000000..a05198d
--- /dev/null
+++ b/docs/PROGRESS.md
@@ -0,0 +1,58 @@
+# Reproduction checkpoint
+
+Objective: reconstruct the complete methodology in colsto's video UytYrhYLOKI,
+and establish what works using reproducible end-to-end tests.
+
+## Current evidence
+
+- Source MP4: `/home/cinna/Downloads/I discovered a sound that leaks your exact location (and it's everywhere) - colsto (1080p).mp4` (1751.53 s).
+- Downloaded the source video's English captions and metadata into `data/source/`.
+- Candidate real validation source: https://zenodo.org/records/23424278,
+ 40 aircraft recordings with timestamped frequency measurements and ADS-B KMLs.
+- Existing MIT implementation https://github.com/mojomast/hermes-aircraft-doppler-geolocation
+ implements ridge extraction and single-event candidate scoring, but not the full pipeline.
+
+## Acceptance criteria
+
+1. Document the source methodology, equations, assumptions and differences.
+2. Implement audio ingestion, spectral measurements, ADS-B ingestion/type filtering,
+ terrain-aware candidate search, delay/Doppler modelling, event pairing and silence
+ filtering, locked multi-event scoring, refinement and reports.
+3. Exercise audio-to-ranked-location runs with withheld synthetic truth, distractors,
+ unknown recording start, multiple events and a known-time short recording.
+4. Run suitable real recordings against their actual independent flight tracks and
+ published recording-position evidence; report errors and failures without
+ substituting synthetic tests for real-world validation.
+5. Leave exact commands, source manifests, tests and measured results.
+
+## Implemented and checked
+
+- Independent implementation in `src/aircraft_geoloc/`: canonical/KML/trace import,
+ WGS84 geometry, sound emission-time solve, Doppler, spectrograms, Viterbi ridge,
+ straight-pass measurements, flight corridor grids, DEM sampling, CPA tables,
+ multi-event time filters, silence filter, shared-clock brightness/ridge scoring,
+ grid refinement and plotted reports.
+- `tests/test_physics.py`: 2 tests passed, including an independent analytic
+ constant-velocity solution at both small and full Unix timestamps.
+- First full run: `results/synthetic-two-events/report.json`; correct flight pair,
+ 21.89 m location error and -0.343 s clock error. Input audio was generated by
+ an independent emission-domain renderer and truth was only read afterward.
+- Synthetic one-minute known-time case is running.
+- Downloaded all 40 paired research recordings with Zenodo checksum verification.
+- Downloaded the video's linked one-hour source audio, and generated an overview
+ spectrogram in `data/source/reference-overview.png`.
+- Video frame 10:35 gives first event 130-154 m/s and 4300-7800 m slant;
+ second 88-110 m/s and 1390-4690 m; offset 920 s. Frame 12:12 specifies
+ silence threshold max(CPA slant of the two events), with no multiplier.
+- Source raw hour has event CPAs near 2156 s and 3076 s (source UI displays
+ times 3600 s later). The automatic tracker can attach to interfering tones;
+ narrow/manual windows remain part of the measured workflow, as in the video.
+- Downloading the open 2026-09-08 ADS-B daily archive; recording year is currently
+ inferred from the video publication and must be checked against actual tracks.
+
+## Next actions
+
+Finish the short-clip test and filter regressions; improve/inspect reference ridge
+measurements; ingest the historical archive, obtain aircraft type and elevation
+data, and run the real reference recording end to end. Real geolocation is not
+yet verified; the synthetic result does not establish the video's national claim.
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..8be5ff6
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,19 @@
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "aircraft-geoloc-reproduction"
+version = "0.1.0"
+description = "Reproducible physics-based aircraft acoustic geolocation"
+requires-python = ">=3.11"
+dependencies = ["numpy", "scipy", "pandas", "soundfile", "pyproj", "rasterio", "matplotlib", "requests", "pyarrow"]
+
+[project.scripts]
+aircraft-geoloc = "aircraft_geoloc.cli:main"
+
+[tool.setuptools.packages.find]
+where = ["src"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
diff --git a/scripts/benchmark_real_features.py b/scripts/benchmark_real_features.py
new file mode 100644
index 0000000..0e0f189
--- /dev/null
+++ b/scripts/benchmark_real_features.py
@@ -0,0 +1,59 @@
+"""Compare audio measurements on all 40 public paired research passages.
+
+The author's annotated harmonic selects the frequency band, as a human would do
+from a spectrogram. ADS-B reference speed/range labels are used only afterward.
+This measures acoustic feature recovery, not recording-location accuracy: this
+dataset does not publish an explicit recorder coordinate or audio-sample UTC clock.
+"""
+import json
+import time
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+import soundfile as sf
+
+from aircraft_geoloc.audio import measure,fit_flyover
+
+root=Path(__file__).resolve().parents[1]
+source=root/"data/research/zenodo-23424278"
+output=root/"results/real-feature-benchmark"
+output.mkdir(parents=True,exist_ok=True)
+references=pd.read_csv(source/"final_results_40_cases.csv")
+results=[]
+for reference in references.itertuples():
+ began=time.monotonic()
+ folder=next((source/"extracted").glob("*/"+reference.case))
+ annotations=pd.read_csv(folder/"frequency_vs_time_used.csv")
+ manual_t=pd.to_datetime(annotations.time_utc).astype("int64").to_numpy()/1e9
+ manual_t-=manual_t[0]
+ manual_f=annotations.frequency_hz.to_numpy()
+ row={"case":reference.case,"category":reference.category,
+ "reference_speed_mps":reference.V_ADSB_at_closest_kmh/3.6,
+ "reference_slant_m":reference.R_ADSB_m}
+ try:
+ # The window is the complete published WAV; selecting a harmonic is the
+ # sole annotation-assisted step in automatic ridge extraction.
+ spread=np.ptp(manual_f)
+ band=[max(10,np.min(manual_f)-max(5,spread*0.08)),np.max(manual_f)+max(5,spread*0.08)]
+ spec,ridge,weight,fit=measure(folder/"audio.wav",{
+ "start_s":0,"end_s":sf.info(folder/"audio.wav").duration,
+ "band_hz":band,"max_slope_hz_s":max(8,spread/12),"max_up_slope_hz_s":1},output/reference.case)
+ manual_fit=fit_flyover(manual_t,manual_f)
+ row.update({"detected":fit["detected"],"audio_fit":fit,"annotation_fit":manual_fit,
+ "speed_error_percent":100*(fit["speed_mps"]/row["reference_speed_mps"]-1),
+ "slant_error_percent":100*(fit["slant_m"]/row["reference_slant_m"]-1),
+ "annotation_speed_error_percent":100*(manual_fit["speed_mps"]/row["reference_speed_mps"]-1),
+ "elapsed_s":time.monotonic()-began})
+ except Exception as exc:
+ row["error"]=f"{type(exc).__name__}: {exc}"
+ results.append(row)
+ (output/"cases.json").write_text(json.dumps(results,indent=2,allow_nan=False)+"\n")
+ print(reference.case,{k:row.get(k) for k in ["detected","speed_error_percent","slant_error_percent","error"]},flush=True)
+detected=[r for r in results if r.get("detected")]
+summary={"cases":len(results),"detected":len(detected),"errors":sum("error" in r for r in results),
+ "median_absolute_speed_error_percent":float(np.median([abs(r["speed_error_percent"]) for r in detected])) if detected else None,
+ "median_absolute_slant_error_percent":float(np.median([abs(r["slant_error_percent"]) for r in detected])) if detected else None,
+ "validation_scope":"harmonic-band-assisted acoustic parameter recovery; not a location benchmark"}
+(output/"summary.json").write_text(json.dumps(summary,indent=2)+"\n")
+print(summary,flush=True)
diff --git a/scripts/fetch_adsblol_day.py b/scripts/fetch_adsblol_day.py
new file mode 100644
index 0000000..73a2940
--- /dev/null
+++ b/scripts/fetch_adsblol_day.py
@@ -0,0 +1,50 @@
+"""Download a preferred open ADS-B daily archive with resumable HTTP ranges.
+
+Archives remain external data; the ODbL provenance and release metadata are kept.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+
+import requests
+
+parser=argparse.ArgumentParser()
+parser.add_argument("date",help="YYYY-MM-DD")
+parser.add_argument("--provider",default="staging-0")
+args=parser.parse_args()
+year=args.date[:4]
+tag=f"v{args.date.replace('-','.')}-planes-readsb-{args.provider}"
+root=Path(__file__).resolve().parents[1]/"data/adsb"/args.date
+root.mkdir(parents=True,exist_ok=True)
+s=requests.Session()
+response=s.get(f"https://api.github.com/repos/adsblol/globe_history_{year}/releases/tags/{tag}",timeout=60)
+response.raise_for_status()
+release=response.json()
+(root/"release.json").write_text(json.dumps(release,indent=2)+"\n")
+for asset in sorted(release["assets"],key=lambda a:a["name"]):
+ path=root/asset["name"]
+ if path.exists() and path.stat().st_size==asset["size"]:
+ print("Already downloaded",path.name,flush=True)
+ continue
+ temporary=path.with_suffix(path.suffix+".part")
+ offset=temporary.stat().st_size if temporary.exists() else 0
+ headers={"Range":f"bytes={offset}-"} if offset else {}
+ r=s.get(asset["browser_download_url"],headers=headers,stream=True,timeout=(30,120))
+ r.raise_for_status()
+ if offset and r.status_code!=206:
+ raise ValueError("Server did not honor resumable range; partial file preserved")
+ print("Downloading",path.name,"bytes",asset["size"],"from",offset,flush=True)
+ with temporary.open("ab" if offset else "wb") as f:
+ for chunk in r.iter_content(4*1024*1024):
+ f.write(chunk)
+ if temporary.stat().st_size!=asset["size"]:
+ raise ValueError("Truncated download; rerun to resume")
+ if asset.get("digest"):
+ algorithm,expected=asset["digest"].split(":")
+ with temporary.open("rb") as f:
+ actual=hashlib.file_digest(f,algorithm).hexdigest()
+ if actual!=expected:
+ raise ValueError("Release asset digest mismatch")
+ temporary.replace(path)
+ print("Complete",path.name,flush=True)
diff --git a/scripts/fetch_research_data.py b/scripts/fetch_research_data.py
new file mode 100644
index 0000000..f2782fd
--- /dev/null
+++ b/scripts/fetch_research_data.py
@@ -0,0 +1,40 @@
+"""Fetch the paired audio/ADS-B research dataset, verifying its checksums."""
+import hashlib
+import json
+import zipfile
+from pathlib import Path
+
+import requests
+
+root = Path(__file__).resolve().parents[1] / "data/research/zenodo-23424278"
+root.mkdir(parents=True, exist_ok=True)
+s = requests.Session()
+r = s.get("https://zenodo.org/api/records/23424278", timeout=60)
+r.raise_for_status()
+record = r.json()
+(root / "record.json").write_text(json.dumps(record, indent=2))
+for item in record["files"]:
+ path = root / item["key"]
+ if not path.exists():
+ print("Downloading", item["key"], item["size"], flush=True)
+ response = s.get(item["links"]["self"], stream=True, timeout=90)
+ response.raise_for_status()
+ temporary = path.with_suffix(path.suffix + ".part")
+ with temporary.open("wb") as f:
+ for chunk in response.iter_content(1024 * 1024):
+ f.write(chunk)
+ temporary.replace(path)
+ algorithm, expected = item["checksum"].split(":")
+ with path.open("rb") as f:
+ actual = hashlib.file_digest(f, algorithm).hexdigest()
+ if actual != expected:
+ raise ValueError(f"Checksum mismatch: {path}")
+ print("Verified", item["key"], flush=True)
+ if path.suffix == ".zip":
+ dest = root / "extracted"
+ with zipfile.ZipFile(path) as archive:
+ for member in archive.infolist():
+ target = (dest / member.filename).resolve()
+ if not target.is_relative_to(dest.resolve()):
+ raise ValueError("Archive member escapes data directory")
+ archive.extractall(dest)
diff --git a/scripts/ingest_adsblol_day.py b/scripts/ingest_adsblol_day.py
new file mode 100644
index 0000000..17417fe
--- /dev/null
+++ b/scripts/ingest_adsblol_day.py
@@ -0,0 +1,91 @@
+"""Stream a split daily tar archive into a CONUS prop/unknown parquet table."""
+import argparse
+import gzip
+import io
+import json
+import tarfile
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+import pyarrow.parquet as pq
+import requests
+
+from aircraft_geoloc.tracks import adsblol_frame
+
+parser=argparse.ArgumentParser()
+parser.add_argument("date")
+args=parser.parse_args()
+root=Path(__file__).resolve().parents[1]
+directory=root/"data/adsb"/args.date
+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)
+ r.raise_for_status()
+ raw=r.content
+ if raw[:2]==b"\x1f\x8b":raw=gzip.decompress(raw)
+ text=raw.decode()
+ # The public database is a JS assignment containing one JSON dictionary.
+ start,end=text.find("{"),text.rfind("}")+1
+ json.loads(text[start:end])
+ types_path.write_text(text[start:end])
+types=json.loads(types_path.read_text())
+print("Type examples",list(types.items())[:3],flush=True)
+engines={}
+for code,value in types.items():
+ classification=value.get("desc","") if isinstance(value,dict) else (value[2] if len(value)>2 else "")
+ engines[code]="Jet" if classification.endswith("J") else "Other/unknown"
+pd.DataFrame({"designator":list(engines),"engine_type":list(engines.values())}).to_csv(directory/"type-database.csv",index=False)
+
+
+class SplitReader(io.RawIOBase):
+ def __init__(self,paths):
+ self.paths=iter(paths)
+ self.current=None
+ def readable(self):return True
+ def readinto(self,b):
+ while True:
+ if self.current is None:
+ path=next(self.paths,None)
+ if path is None:return 0
+ self.current=open(path,"rb")
+ n=self.current.readinto(b)
+ if n:return n
+ self.current.close();self.current=None
+
+
+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}
+writer=None
+with io.BufferedReader(SplitReader(paths),buffer_size=1024*1024) as stream:
+ with 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()
+ d=json.loads(gzip.decompress(raw) if raw[:2]==b"\x1f\x8b" else raw)
+ stats["trace_files"]+=1
+ if engines.get(d.get("t",""))=="Jet":
+ stats["known_jets_removed"]+=1
+ continue
+ trace=[p for p in d.get("trace",[]) if p[1] is not None and p[2] is not None and 24<=p[1]<=50 and -125<=p[2]<=-66]
+ if not trace:
+ stats["no_conus_points"]+=1
+ continue
+ d["trace"]=trace
+ frame=adsblol_frame(d)
+ if frame.empty:continue
+ 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.
+ 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/"conus-prop-unknown.parquet",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/"ingestion-report.json").write_text(json.dumps(stats,indent=2)+"\n")
+print(stats,flush=True)
diff --git a/scripts/make_synthetic_cases.py b/scripts/make_synthetic_cases.py
new file mode 100644
index 0000000..d55f2a3
--- /dev/null
+++ b/scripts/make_synthetic_cases.py
@@ -0,0 +1,90 @@
+"""Make blind end-to-end cases with an independent emission-domain renderer.
+
+The renderer never calls the search's acoustic/Doppler code. It transports a
+source oscillator into receiver time, making a wrong delay law fail validation.
+Truth is written separately and is never read by the search pipeline.
+"""
+import json
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+from pyproj import Transformer
+import soundfile as sf
+
+
+root=Path(__file__).resolve().parents[1]
+out=root/"data/synthetic"
+out.mkdir(parents=True,exist_ok=True)
+rng=np.random.default_rng(78139)
+epoch=1790000000.0
+sr=4000
+duration=1180
+receiver_time=np.arange(duration*sr)/sr
+audio=rng.normal(0,0.8,len(receiver_time))
+audio+=0.08*np.sin(2*np.pi*60*receiver_time)+0.05*np.sin(2*np.pi*180*receiver_time)
+earth=Transformer.from_crs("EPSG:4979","EPSG:4978",always_xy=True)
+
+
+def positions(t,event,variant=0):
+ if event==0:
+ return 88*t+0.045*t*t,1000+0.10*t*t+variant*0.0015*t**3,1500+0.4*t
+ return -700+0.08*t*t+variant*0.0008*t**3,75*t-0.025*t*t,1100+0.8*t
+
+
+rows=[]
+truth={"lat":40.03173,"lon":-100.01829,"elev_m":120.0,"recording_start_time_s":epoch,
+ "flight_ids":["true-A","true-B"],"f0_hz":[135.0,115.0]}
+for region,(lat0,lon0) in enumerate([(40.0,-100.0),(35.0,-90.0),(43.0,-112.0)]):
+ local=f"+proj=aeqd +lat_0={lat0} +lon_0={lon0} +datum=WGS84 +units=m"
+ inverse=Transformer.from_crs(local,"EPSG:4326",always_xy=True)
+ forward=Transformer.from_crs("EPSG:4326",local,always_xy=True)
+ # In the true region the receiver is off the path coordinate origin and off
+ # every 200/100/25 m global grid, so including truth as a grid point is impossible.
+ ox,oy=forward.transform(truth["lon"],truth["lat"]) if region==0 else (0,0)
+ observer=np.array(earth.transform(truth["lon"],truth["lat"],truth["elev_m"]))
+ for event,center in enumerate([150.0,1070.0]):
+ identifier=("true" if region==0 else f"false{region}")+"-"+"AB"[event]
+ t=np.arange(-115,116,1.0)
+ x,y,h=positions(t,event,region)
+ lon,lat=inverse.transform(x+ox,y+oy)
+ for j in range(len(t)):
+ rows.append({"flight_id":identifier,"time_s":epoch+center+t[j],"lat":lat[j],
+ "lon":lon[j],"alt_m":h[j]+120,"typecode":"C172"})
+ if region==0:
+ te=np.arange(-115,115,1/sr)
+ x,y,h=positions(te,event)
+ lon,lat=inverse.transform(x+ox,y+oy)
+ xyz=np.column_stack(earth.transform(lon,lat,h+120))
+ distance=np.linalg.norm(xyz-observer,axis=1)
+ arrival=center+te+distance/343.0
+ amplitude=0.16*np.minimum(1,1800/distance)
+ # Weak second harmonic and a smoothly varying acoustic envelope.
+ f0=truth["f0_hz"][event]
+ emitted=amplitude*(np.sin(2*np.pi*f0*te)+0.35*np.sin(2*np.pi*2*f0*te+0.4))
+ audio+=np.interp(receiver_time,arrival,emitted,left=0,right=0)
+ truth.setdefault("events",[]).append({"flight_id":identifier,"center_emission_s":center})
+
+# A known jet with a plausible path must be excluded by classification. An unknown
+# designator is retained to avoid reproducing the opposite (unsafe) type filter.
+jet=[dict(r,flight_id="known-jet",typecode="A320") for r in rows if r["flight_id"]=="false1-A"]
+rows+=jet
+pd.DataFrame(rows).to_csv(out/"tracks.csv",index=False)
+pd.DataFrame({"designator":["A320","C172"],"engine_type":["Jet","Piston"]}).to_csv(out/"types.csv",index=False)
+sf.write(out/"recording.wav",audio/5,sr,subtype="FLOAT")
+config={"audio":"recording.wav","tracks":["tracks.csv"],"type_database":"types.csv",
+ "terrain":{"constant_m":120},"grid":{"spacing_m":200,"scoring_spacing_m":100,"refine_spacing_m":25,"refine_pairs":3},
+ "events":[{"start_s":65,"end_s":250,"band_hz":[95,185],"speed_range_mps":[60,120],"slant_range_m":[1300,2500],"f0_range_hz":[132,138]},
+ {"start_s":985,"end_s":1170,"band_hz":[80,155],"speed_range_mps":[50,105],"slant_range_m":[1000,2200],"f0_range_hz":[112,118]}],
+ "filters":{"offset_tolerance_s":6,"silence":{"edge_margin_s":100}},
+ "scoring":{"mode":"brightness","time_sweep_s":3,"time_step_s":0.5}}
+(out/"two-events.json").write_text(json.dumps(config,indent=2)+"\n")
+single=json.loads(json.dumps(config))
+single["recording_start_utc"]=epoch
+single["events"]=[dict(config["events"][0],start_s=123,end_s=183)]
+single["scoring"]["mode"]="ridge"
+single["scoring"]["time_sweep_s"]=0.5
+single["filters"]={"known_time_tolerance_s":5}
+(out/"known-time-minute.json").write_text(json.dumps(single,indent=2)+"\n")
+(out/"truth.json").write_text(json.dumps(truth,indent=2)+"\n")
+print(out)
diff --git a/scripts/prepare_source.py b/scripts/prepare_source.py
new file mode 100644
index 0000000..455ae9d
--- /dev/null
+++ b/scripts/prepare_source.py
@@ -0,0 +1,36 @@
+"""Normalize downloaded rolling captions and fingerprint the supplied MP4."""
+import hashlib
+import html
+import json
+import re
+from pathlib import Path
+
+root = Path(__file__).resolve().parents[1]
+source = root / "data/source"
+raw = (source / "video.en.vtt").read_text()
+segments = []
+previous = ""
+for block in re.split(r"\n\s*\n", raw):
+ lines = block.splitlines()
+ timing = next((line for line in lines if " --> " in line), None)
+ if timing is None:
+ continue
+ start = timing.split()[0]
+ hh, mm, ss = map(float, start.split(":"))
+ for line in lines[lines.index(timing) + 1:]:
+ line = html.unescape(re.sub(r"<[^>]+>", "", line)).strip()
+ if line and line != previous:
+ segments.append({"time_s": hh * 3600 + mm * 60 + ss, "text": line})
+ previous = line
+(source / "transcript.json").write_text(json.dumps(segments, indent=2) + "\n")
+(source / "transcript.txt").write_text("\n".join(
+ f"[{int(s['time_s']) // 60:02d}:{int(s['time_s']) % 60:02d}] {s['text']}" for s in segments
+) + "\n")
+video = next(Path("/home/cinna/Downloads").glob("I discovered a sound*colsto*.mp4"))
+digest = hashlib.file_digest(video.open("rb"), "sha256").hexdigest()
+(source / "source_manifest.json").write_text(json.dumps({
+ "video_path": str(video), "sha256": digest, "bytes": video.stat().st_size,
+ "source_url": "https://www.youtube.com/watch?v=UytYrhYLOKI",
+ "caption_type": "YouTube automatic English captions; uncorrected",
+}, indent=2) + "\n")
+print(f"Prepared {len(segments)} transcript lines; MP4 SHA256 {digest}")
diff --git a/src/aircraft_geoloc/__init__.py b/src/aircraft_geoloc/__init__.py
new file mode 100644
index 0000000..c26c1d3
--- /dev/null
+++ b/src/aircraft_geoloc/__init__.py
@@ -0,0 +1 @@
+"""Aircraft-acoustic geolocation reproduction."""
diff --git a/src/aircraft_geoloc/audio.py b/src/aircraft_geoloc/audio.py
new file mode 100644
index 0000000..da3878f
--- /dev/null
+++ b/src/aircraft_geoloc/audio.py
@@ -0,0 +1,164 @@
+"""Audio ingestion, narrow-band spectrograms and reproducible Doppler measurements."""
+from dataclasses import dataclass
+import json
+import subprocess
+
+import numpy as np
+from scipy import ndimage, optimize, signal
+
+from .geometry import straight_doppler
+
+
+def decode(path, start=0.0, duration=None, sample_rate=4000):
+ command = ["ffmpeg", "-v", "error", "-ss", str(start), "-i", str(path)]
+ if duration is not None:
+ command += ["-t", str(duration)]
+ command += ["-vn", "-ac", "1", "-ar", str(sample_rate), "-f", "f32le", "pipe:1"]
+ result = subprocess.run(command, capture_output=True, check=True)
+ data = np.frombuffer(result.stdout, dtype="<f4").astype(float)
+ if not len(data) or not np.all(np.isfinite(data)):
+ raise ValueError(f"Invalid/empty decoded audio: {path}")
+ return data, sample_rate
+
+
+@dataclass
+class Spectrum:
+ time: np.ndarray
+ frequency: np.ndarray
+ db: np.ndarray
+ contrast: np.ndarray
+
+ def sample(self, t, f):
+ """Bilinear contrast along a template; unsupported samples stay NaN."""
+ ti = (np.asarray(t) - self.time[0]) / (self.time[1] - self.time[0])
+ fi = (np.asarray(f) - self.frequency[0]) / (self.frequency[1] - self.frequency[0])
+ ti, fi = np.broadcast_arrays(ti, fi)
+ values = ndimage.map_coordinates(self.contrast, [fi.ravel(), ti.ravel()],
+ order=1, mode="constant", cval=np.nan)
+ return values.reshape(ti.shape)
+
+
+def spectrogram(data, sample_rate, band, start=0.0, window_s=2.0, hop_s=0.25):
+ n = int(sample_rate * window_s)
+ hop = int(sample_rate * hop_s)
+ if len(data) < n:
+ raise ValueError("Event is shorter than the spectral analysis window")
+ f, t, power = signal.spectrogram(data, fs=sample_rate, window="hann", nperseg=n,
+ noverlap=n - hop, nfft=4 * n, scaling="density")
+ keep = (f >= band[0]) & (f <= band[1])
+ f, power = f[keep], power[keep]
+ db = 10 * np.log10(power + np.finfo(float).tiny)
+ # Suppress stationary tones, then normalize each time column by its robust
+ # noise floor. This is a numeric analogue of increasing spectrogram contrast.
+ whitened = db - np.median(db, axis=1, keepdims=True)
+ center = np.median(whitened, axis=0, keepdims=True)
+ scale = 1.4826 * np.median(np.abs(whitened - center), axis=0, keepdims=True)
+ contrast = np.clip((whitened - center) / np.maximum(scale, 1.0), -4, 12)
+ return Spectrum(t + start, f, db, contrast)
+
+
+def trace_ridge(spectrum, max_slope=12.0, smoothness=0.12, max_up_slope=1.0):
+ """Viterbi ridge with a bounded frequency change and quadratic transition cost."""
+ strength = np.clip(spectrum.contrast, -2, 7)
+ df = spectrum.frequency[1] - spectrum.frequency[0]
+ dt = spectrum.time[1] - spectrum.time[0]
+ width = max(1, int(np.ceil(max_slope * dt / df)))
+ nf, nt = strength.shape
+ history = np.zeros((nt, nf), dtype=np.int16)
+ state = strength[:, 0].copy()
+ frequency_index = np.arange(nf)
+ for j in range(1, nt):
+ best = np.full(nf, -np.inf)
+ parent = np.zeros(nf, dtype=np.int16)
+ up_width = max(0, int(np.floor(max_up_slope * dt / df)))
+ for shift in range(-up_width, width + 1):
+ previous = frequency_index + shift
+ valid = (previous >= 0) & (previous < nf)
+ score = np.full(nf, -np.inf)
+ score[valid] = state[previous[valid]] - smoothness * (shift * df / dt) ** 2 * dt
+ better = score > best
+ best[better] = score[better]
+ parent[better] = previous[better]
+ state = best + strength[:, j]
+ history[j] = parent
+ path = np.empty(nt, dtype=int)
+ path[-1] = np.argmax(state)
+ for j in range(nt - 1, 0, -1):
+ path[j - 1] = history[j, path[j]]
+ # Sub-bin parabolic interpolation improves ridge precision without claiming
+ # that zero padding itself increased the physical spectral resolution.
+ interior = np.clip(path, 1, nf - 2)
+ cols = np.arange(nt)
+ a, b, c = (spectrum.db[interior + offset, cols] for offset in (-1, 0, 1))
+ shift = np.clip(0.5 * (a - c) / np.where(np.abs(a - 2*b + c) > 1e-9, a - 2*b + c, -1), -0.5, 0.5)
+ frequency = spectrum.frequency[interior] + shift * df
+ weight = np.clip(spectrum.contrast[path, cols], 0, 8)
+ return frequency, weight
+
+
+def fit_flyover(t, frequency, weight=None, c=343.0):
+ t, frequency = np.asarray(t), np.asarray(frequency)
+ weight = np.ones(len(t)) if weight is None else np.maximum(np.asarray(weight), 0.05)
+ weight /= np.mean(weight)
+ middle = (t[0] + t[-1]) / 2
+ x = t - middle
+ initial = [np.median(frequency), 80.0, 1500.0, 0.0]
+ bounds = ([np.min(frequency)*0.5, 10, 50, x[0]],
+ [np.max(frequency)*1.5, min(250, c*0.85), 20000, x[-1]])
+ result = optimize.least_squares(
+ lambda p: (straight_doppler(x, *p, c=c) - frequency) * np.sqrt(weight),
+ initial, bounds=bounds, loss="soft_l1", f_scale=1.0, x_scale="jac", max_nfev=1000)
+ residual = straight_doppler(x, *result.x, c=c) - frequency
+ f0, speed, slant, tc = result.x
+ return {"f0_hz": float(f0), "speed_mps": float(speed), "slant_m": float(slant),
+ "cpa_receive_s": float(tc + middle),
+ "rmse_hz": float(np.sqrt(np.average(residual**2, weights=weight))),
+ "frequency_drop_hz": float(np.percentile(frequency[:max(3,len(t)//8)],50) -
+ np.percentile(frequency[-max(3,len(t)//8):],50)),
+ "optimizer_success": bool(result.success)}
+
+
+def measure(path, settings, output=None):
+ data, sr = decode(path, settings["start_s"], settings["end_s"] - settings["start_s"])
+ spec = spectrogram(data, sr, settings["band_hz"], settings["start_s"],
+ settings.get("window_s", 2.0), settings.get("hop_s", 0.25))
+ if settings.get("ridge_csv"):
+ ridge = np.genfromtxt(settings["ridge_csv"], names=True, delimiter=",")
+ frequency = np.interp(spec.time, ridge["time_s"], ridge["frequency_hz"], left=np.nan, right=np.nan)
+ weight = np.ones(len(frequency))
+ else:
+ frequency, weight = trace_ridge(spec, settings.get("max_slope_hz_s", 12),
+ max_up_slope=settings.get("max_up_slope_hz_s",1.0))
+ valid = np.isfinite(frequency)
+ fit = fit_flyover(spec.time[valid], frequency[valid], weight[valid])
+ fit["ridge_contrast"] = float(np.median(spec.sample(spec.time[valid], frequency[valid])))
+ fit["detected"] = bool(fit["ridge_contrast"] >= settings.get("min_contrast", 1.5)
+ and fit["frequency_drop_hz"] >= settings.get("min_drop_hz", 4)
+ and fit["rmse_hz"] <= settings.get("max_fit_rmse_hz", 8))
+ if output:
+ from pathlib import Path
+ prefix = Path(output)
+ prefix.parent.mkdir(parents=True, exist_ok=True)
+ prefix.with_suffix(".json").write_text(json.dumps(fit, indent=2) + "\n")
+ np.savetxt(prefix.with_suffix(".csv"), np.column_stack((spec.time, frequency, weight)),
+ delimiter=",", header="time_s,frequency_hz,weight", comments="")
+ np.savez_compressed(prefix.with_suffix(".npz"), time=spec.time, frequency=spec.frequency,
+ db=spec.db, contrast=spec.contrast, ridge=frequency, weight=weight)
+ plot_measurement(spec, frequency, fit, prefix.with_suffix(".png"))
+ return spec, frequency, weight, fit
+
+
+def plot_measurement(spec, ridge, fit, path):
+ import matplotlib
+ matplotlib.use("Agg")
+ from matplotlib import pyplot as plt
+ fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
+ ax.pcolormesh(spec.time, spec.frequency, spec.contrast, shading="auto", cmap="magma", vmin=0, vmax=6)
+ ax.plot(spec.time, ridge, color="cyan", lw=0.8, label="Measured ridge")
+ ax.plot(spec.time, straight_doppler(spec.time, fit["f0_hz"], fit["speed_mps"],
+ fit["slant_m"], fit["cpa_receive_s"]), color="lime", lw=1, label="Straight-pass fit")
+ ax.set(xlabel="Recording time (s)", ylabel="Frequency (Hz)",
+ title=f"v={fit['speed_mps']:.1f} m/s; slant={fit['slant_m']:.0f} m; residual={fit['rmse_hz']:.2f} Hz")
+ ax.legend(loc="upper right")
+ fig.savefig(path, dpi=150)
+ plt.close(fig)
diff --git a/src/aircraft_geoloc/cli.py b/src/aircraft_geoloc/cli.py
new file mode 100644
index 0000000..97b0470
--- /dev/null
+++ b/src/aircraft_geoloc/cli.py
@@ -0,0 +1,28 @@
+import argparse
+import json
+
+
+def main():
+ parser=argparse.ArgumentParser(description="Aircraft acoustic geolocation research pipeline")
+ sub=parser.add_subparsers(dest="command",required=True)
+ run=sub.add_parser("run",help="Measure events, filter geometry, rank and refine locations")
+ run.add_argument("config")
+ run.add_argument("--output",required=True)
+ measure=sub.add_parser("measure",help="Measure one Doppler event without locating it")
+ measure.add_argument("audio")
+ measure.add_argument("--start",type=float,required=True)
+ measure.add_argument("--end",type=float,required=True)
+ measure.add_argument("--band",type=float,nargs=2,required=True)
+ measure.add_argument("--output",required=True)
+ args=parser.parse_args()
+ if args.command=="run":
+ from .pipeline import run
+ run(args.config,args.output)
+ elif args.command=="measure":
+ from .audio import measure
+ result=measure(args.audio,{"start_s":args.start,"end_s":args.end,"band_hz":args.band},args.output)
+ print(json.dumps(result[-1],indent=2))
+
+
+if __name__=="__main__":
+ main()
diff --git a/src/aircraft_geoloc/geometry.py b/src/aircraft_geoloc/geometry.py
new file mode 100644
index 0000000..1817251
--- /dev/null
+++ b/src/aircraft_geoloc/geometry.py
@@ -0,0 +1,123 @@
+"""3-D geometry and emission-time acoustic propagation, in SI units.
+
+Range rate is positive for a receding source. Observer and aircraft heights must
+use the same vertical datum. ECEF treats those heights as ellipsoidal; supplying
+orthometric heights to both is a documented common-datum approximation.
+"""
+from dataclasses import dataclass
+
+import numpy as np
+from scipy.interpolate import CubicHermiteSpline
+from scipy.optimize import minimize_scalar
+from scipy.signal import find_peaks
+
+
+def ecef(lat, lon, height):
+ lat, lon, height = np.broadcast_arrays(np.deg2rad(lat), np.deg2rad(lon), height)
+ a, e2 = 6378137.0, 6.6943799901413165e-3
+ n = a / np.sqrt(1 - e2 * np.sin(lat) ** 2)
+ return np.stack(((n + height) * np.cos(lat) * np.cos(lon),
+ (n + height) * np.cos(lat) * np.sin(lon),
+ (n * (1 - e2) + height) * np.sin(lat)), axis=-1)
+
+
+def velocity_ecef(lat, lon, east, north, up):
+ lat, lon = np.deg2rad(lat), np.deg2rad(lon)
+ return np.stack((-np.sin(lon) * east - np.sin(lat) * np.cos(lon) * north + np.cos(lat) * np.cos(lon) * up,
+ np.cos(lon) * east - np.sin(lat) * np.sin(lon) * north + np.cos(lat) * np.sin(lon) * up,
+ np.cos(lat) * north + np.sin(lat) * up), axis=-1)
+
+
+@dataclass
+class Track:
+ id: str
+ time: np.ndarray
+ lat: np.ndarray
+ lon: np.ndarray
+ altitude: np.ndarray
+ typecode: str = ""
+ velocity: np.ndarray | None = None
+
+ def __post_init__(self):
+ self.time, self.lat, self.lon, self.altitude = [np.asarray(a, dtype=float) for a in
+ (self.time, self.lat, self.lon, self.altitude)]
+ if len(self.time) < 3 or not np.all(np.diff(self.time) > 0):
+ raise ValueError(f"{self.id}: need >=3 strictly ordered unique timestamps")
+ if not np.all(np.isfinite(np.column_stack((self.time, self.lat, self.lon, self.altitude)))):
+ raise ValueError(f"{self.id}: nonfinite track data")
+ self.xyz = ecef(self.lat, self.lon, self.altitude)
+ self.origin = self.time[0]
+ self.relative_time = self.time - self.origin
+ v = self.velocity
+ if v is None:
+ v = np.gradient(self.xyz, self.relative_time, axis=0)
+ self.spline = CubicHermiteSpline(self.relative_time, self.xyz, v, extrapolate=False)
+ self.derivative = self.spline.derivative()
+
+ def position(self, t):
+ return self.spline(np.asarray(t) - self.origin)
+
+ def speed_vector(self, t):
+ return self.derivative(np.asarray(t) - self.origin)
+
+ def acoustic(self, receive_time, observer, c=343.0):
+ """Return Doppler factor, emission time and range at receiver-clock times.
+
+ Solve t_receive = t_emit + |x(t_emit)-observer|/c with Newton's method.
+ Values outside the supported emission interval are NaN, never extrapolated.
+ """
+ t = np.asarray(receive_time, dtype=float)
+ start, end = self.time[[0, -1]]
+ arrival_start = start + np.linalg.norm(self.xyz[0] - observer) / c
+ arrival_end = end + np.linalg.norm(self.xyz[-1] - observer) / c
+ supported = (t >= arrival_start) & (t <= arrival_end)
+ initial = self.position(np.clip(t, start, end))
+ tau = np.clip(t - np.linalg.norm(initial - observer, axis=-1) / c, start, end)
+ for _ in range(10):
+ delta = self.position(tau) - observer
+ distance = np.linalg.norm(delta, axis=-1)
+ radial = np.sum(delta * self.speed_vector(tau), axis=-1) / distance
+ derivative = 1 + radial / c
+ if np.any(derivative <= 0):
+ raise ValueError("Acoustic model requires a subsonic source")
+ correction = (tau - t + distance / c) / derivative
+ tau = np.clip(tau - correction, start, end)
+ if np.max(np.abs(correction)) < 1e-7:
+ break
+ delta = self.position(tau) - observer
+ distance = np.linalg.norm(delta, axis=-1)
+ radial = np.sum(delta * self.speed_vector(tau), axis=-1) / distance
+ factor = c / (c + radial)
+ return tuple(np.where(supported, a, np.nan) for a in (factor, tau, distance))
+
+ def closest_approaches(self, observer, max_distance=np.inf, c=343.0, step=2.0):
+ """All interior local 3-D minima, including repeated passes by one flight."""
+ sample = np.unique(np.r_[np.arange(self.time[0], self.time[-1], step), self.time[-1]])
+ range2 = np.sum((self.position(sample) - observer) ** 2, axis=-1)
+ indices = find_peaks(-range2)[0]
+ events = []
+ for i in indices:
+ # Optimize relative time: scipy's absolute-time stopping term
+ # is too loose when Unix timestamps are around 1.8 billion seconds.
+ mid = sample[i]
+ result = minimize_scalar(lambda dt: np.sum((self.position(mid + dt) - observer) ** 2),
+ bounds=(sample[i - 1] - mid, sample[i + 1] - mid),
+ method="bounded", options={"xatol": 0.001})
+ t = mid + result.x
+ distance = np.sqrt(result.fun)
+ if distance <= max_distance:
+ events.append({"flight_id": self.id, "emission_time": float(t),
+ "receive_time": float(t + distance / c),
+ "distance_m": float(distance),
+ "speed_mps": float(np.linalg.norm(self.speed_vector(t)))})
+ return events
+
+
+def straight_doppler(t_receive, f0, speed, slant, cpa_receive, c=343.0):
+ """Exact retarded-time solution for a constant-speed straight flyover."""
+ # Relative emission t=0 is geometric CPA; its sound arrives at slant/c.
+ u = np.asarray(t_receive) - cpa_receive + slant / c
+ beta = speed / c
+ tau = (u - np.sqrt((beta * u) ** 2 + (1 - beta ** 2) * (slant / c) ** 2)) / (1 - beta ** 2)
+ radial = speed ** 2 * tau / np.sqrt(slant ** 2 + (speed * tau) ** 2)
+ return f0 * c / (c + radial)
diff --git a/src/aircraft_geoloc/pipeline.py b/src/aircraft_geoloc/pipeline.py
new file mode 100644
index 0000000..2e2056e
--- /dev/null
+++ b/src/aircraft_geoloc/pipeline.py
@@ -0,0 +1,174 @@
+"""One command from recording + flight data to ranked, plotted locations."""
+import hashlib
+import json
+import time
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+from .audio import measure
+from .geometry import ecef
+from .search import cpa_table,pair_candidates,rank_candidates
+from .terrain import Terrain,corridor_grid,refine_grid
+from .tracks import load_tracks,unix_time
+
+
+def dump(path,value):
+ Path(path).write_text(json.dumps(value,indent=2,allow_nan=False)+"\n")
+
+
+def run(config_path,output_dir):
+ began=time.monotonic()
+ config_path=Path(config_path).resolve()
+ config=json.loads(config_path.read_text())
+ output=Path(output_dir).resolve()
+ output.mkdir(parents=True,exist_ok=True)
+ def local(path):
+ p=Path(path)
+ return p if p.is_absolute() else config_path.parent/p
+ audio=local(config["audio"])
+ measurements=[]
+ events=[]
+ for i,settings in enumerate(config["events"]):
+ settings=dict(settings)
+ if settings.get("ridge_csv"):
+ settings["ridge_csv"]=str(local(settings["ridge_csv"]))
+ result=measure(audio,settings,output/f"event-{i+1}")
+ fit=result[-1]
+ print("Event",i+1,json.dumps(fit),flush=True)
+ if not fit["detected"] and not settings.get("ridge_csv"):
+ raise ValueError(f"Event {i+1} lacks a supported Doppler detection; inspect its spectrogram")
+ settings.setdefault("cpa_receive_s",fit["cpa_receive_s"])
+ settings.setdefault("speed_range_mps",[max(10,fit["speed_mps"]*0.75),min(260,fit["speed_mps"]*1.25)])
+ settings.setdefault("slant_range_m",[max(50,fit["slant_m"]*0.6),fit["slant_m"]*1.5])
+ settings.setdefault("f0_range_hz",[fit["f0_hz"]-max(3,fit["f0_hz"]*0.02),fit["f0_hz"]+max(3,fit["f0_hz"]*0.02)])
+ measurements.append(result)
+ events.append(settings)
+ if any(events[i]["cpa_receive_s"]>=events[i+1]["cpa_receive_s"] for i in range(len(events)-1)):
+ raise ValueError("Events must be in chronological recording order")
+ tracks=[]
+ imports=[]
+ source_paths=[audio]
+ origin=unix_time(config["recording_start_utc"]) if config.get("recording_start_utc") is not None else None
+ bounds=config.get("grid",{}).get("bounds")
+ track_bounds=None
+ if bounds:
+ # Preserve enough pre/post-event trajectory to model the entire audible
+ # window, not just positions lying within the observer search rectangle.
+ margin=max(e["slant_range_m"][1]+(e["end_s"]-e["start_s"])*e["speed_range_mps"][1] for e in events)/70000+0.1
+ track_bounds=[bounds[0]-margin,bounds[1]-margin,bounds[2]+margin,bounds[3]+margin]
+ time_range=None if origin is None else [origin+events[0]["start_s"]-120,origin+events[-1]["end_s"]+120]
+ for path in config["tracks"]:
+ path=local(path)
+ imported,report=load_tracks(path,max_gap_s=config.get("max_track_gap_s",30),
+ type_database=local(config["type_database"]) if config.get("type_database") else None,
+ bounds=track_bounds,time_range=time_range)
+ tracks.extend(imported)
+ imports.append(dict(report,path=str(path)))
+ source_paths.append(path)
+ if len({t.id for t in tracks})!=len(tracks):
+ raise ValueError("Flight IDs must identify unique imported trajectory segments")
+ if not tracks:
+ raise ValueError("No usable flight trajectories")
+ ground=config["terrain"]
+ terrain=Terrain([local(p) for p in ground.get("rasters",[])],ground.get("constant_m"),
+ local(ground["geoid_raster"]) if ground.get("geoid_raster") else None)
+ grid=config.get("grid",{})
+ coarse=grid.get("spacing_m",200)
+ crs=grid.get("crs","EPSG:5070")
+ points=corridor_grid(tracks,events,coarse,terrain,crs,grid.get("bounds"),origin)
+ print(f"Grid: {len(points)} points; {len(tracks)} trajectory segments",flush=True)
+ radius=max(event["slant_range_m"][1] for event in events)
+ c=config.get("sound_speed_mps",343.0)
+ filters=config.get("filters",{})
+ def select(points):
+ table=cpa_table(tracks,points,radius,c,config.get("cpa_step_s",2))
+ candidates,counts=pair_candidates(table,events,
+ offset_tolerance_s=filters.get("offset_tolerance_s",5),time_origin=origin,
+ time_tolerance_s=filters.get("known_time_tolerance_s",5),silence=filters.get("silence"))
+ return candidates,counts
+ candidates,counts=select(points)
+ dump(output/"filter-counts.json",counts)
+ print("Coarse filters:",counts,flush=True)
+ if not candidates:
+ raise ValueError("No candidates survived; see filter-counts.json")
+ points.to_csv(output/"coarse-grid.csv",index=False)
+ dump(output/"measured-events.json",events)
+ fine=grid.get("scoring_spacing_m",100)
+ if fine<coarse:
+ ids={candidate["point_id"] for candidate in candidates}
+ points=refine_grid(points[points.point_id.isin(ids)],coarse,fine,terrain,crs)
+ candidates,fine_counts=select(points)
+ else:
+ fine_counts=counts
+ print("Scoring filters:",fine_counts,flush=True)
+ dump(output/"scoring-filter-counts.json",fine_counts)
+ scoring=config.get("scoring",{})
+ parameters=dict(mode=scoring.get("mode","brightness"),time_origin=origin,
+ time_sweep_s=scoring.get("time_sweep_s",5),time_step_s=scoring.get("time_step_s",0.5),c=c)
+ ranked=rank_candidates(candidates,points,tracks,events,measurements,**parameters)
+ if not ranked:
+ raise ValueError("No candidate had complete model support in all event windows")
+ dump(output/"ranked-grid.json",ranked)
+ # Refine the best location from each flight combination rather than spending
+ # every refinement slot on neighbouring points of the winning combination.
+ best_pairs={}
+ for row in ranked:
+ best_pairs.setdefault(tuple(row["flight_ids"]),row)
+ chosen=list(best_pairs.values())[:grid.get("refine_pairs",10)]
+ final_spacing=grid.get("refine_spacing_m",25)
+ if final_spacing<fine:
+ seeds=pd.DataFrame(chosen)
+ points2=refine_grid(seeds,fine,final_spacing,terrain,crs)
+ candidates2,refined_counts=select(points2)
+ ranked2=rank_candidates(candidates2,points2,tracks,events,measurements,**parameters)
+ ranked=sorted(ranked+ranked2,key=lambda r:r["score"],reverse=True)
+ dump(output/"refinement-filter-counts.json",refined_counts)
+ best_pairs={}
+ for row in ranked:
+ best_pairs.setdefault(tuple(row["flight_ids"]),row)
+ dump(output/"ranked.json",ranked)
+ dump(output/"flight-combinations.json",list(best_pairs.values()))
+ provenance=[]
+ for path in source_paths:
+ with path.open("rb") as f:
+ digest=hashlib.file_digest(f,"sha256").hexdigest()
+ provenance.append({"path":str(path.resolve()),"sha256":digest})
+ report={"config":config,"measured_events":events,"imports":imports,"sources":provenance,
+ "coarse_filter_counts":counts,"scoring_filter_counts":fine_counts,
+ "ranked_points":len(ranked),"flight_combinations":len(best_pairs),"best":ranked[0],
+ "elapsed_s":time.monotonic()-began,
+ "scoring_time_is_locked":True,"ground_truth_used_by_search":False}
+ dump(output/"report.json",report)
+ plot_results(output,ranked,tracks,measurements)
+ print("Best:",json.dumps(ranked[0]),flush=True)
+ return report
+
+
+def plot_results(output,ranked,tracks,measurements):
+ import matplotlib
+ matplotlib.use("Agg")
+ from matplotlib import pyplot as plt
+ selected=[r for r in ranked if r["flight_ids"]==ranked[0]["flight_ids"]]
+ fig,ax=plt.subplots(figsize=(7,6),layout="constrained")
+ im=ax.scatter([r["lon"] for r in selected],[r["lat"] for r in selected],
+ c=[r["score"] for r in selected],s=12,cmap="viridis")
+ ax.scatter(ranked[0]["lon"],ranked[0]["lat"],marker="*",s=120,color="red",label="Highest score")
+ ax.set(xlabel="Longitude",ylabel="Latitude",title="Location scores for the best flight combination")
+ ax.legend()
+ fig.colorbar(im,ax=ax,label="Score (higher is better)")
+ fig.savefig(output/"location-scores.png",dpi=160)
+ plt.close(fig)
+ lookup={t.id:t for t in tracks}
+ for i,(spec,ridge,weight,fit) in enumerate(measurements):
+ best=ranked[0]
+ track=lookup[best["flight_ids"][i]]
+ factor,_,_=track.acoustic(best["recording_start_time_s"]+spec.time,ecef(best["lat"],best["lon"],best["elev_m"]))
+ fig,ax=plt.subplots(figsize=(10,4),layout="constrained")
+ ax.pcolormesh(spec.time,spec.frequency,spec.contrast,shading="auto",cmap="magma",vmin=0,vmax=6)
+ ax.plot(spec.time,best["f0_hz"][i]*factor,color="cyan",lw=1.1,label="Best physical model")
+ ax.set(xlabel="Recording time (s)",ylabel="Frequency (Hz)",title=f"Event {i+1}: shared clock, {track.id}")
+ ax.legend(loc="upper right")
+ fig.savefig(output/f"event-{i+1}-best-model.png",dpi=160)
+ plt.close(fig)
diff --git a/src/aircraft_geoloc/search.py b/src/aircraft_geoloc/search.py
new file mode 100644
index 0000000..9146a44
--- /dev/null
+++ b/src/aircraft_geoloc/search.py
@@ -0,0 +1,160 @@
+"""Geometric event filters, silence constraints and locked multi-event scoring."""
+from itertools import product
+
+import numpy as np
+import pandas as pd
+from scipy.signal import find_peaks
+from scipy.spatial import cKDTree
+
+from .geometry import ecef
+
+
+def cpa_table(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256):
+ """Vectorized piecewise-linear CPA prefilter; supports repeated local passes.
+
+ This is the inexpensive first stage. Final scoring evaluates the interpolated
+ trajectory and retarded emission time directly, rather than these CPA samples.
+ """
+ observers = ecef(points.lat.to_numpy(),points.lon.to_numpy(),points.elev_m.to_numpy())
+ rows = []
+ for track in tracks:
+ t = np.unique(np.r_[np.arange(track.time[0],track.time[-1],step_s),track.time[-1]])
+ pos = track.position(t)
+ delta = np.diff(pos,axis=0)
+ length2 = np.sum(delta**2,axis=1)
+ supported = np.isfinite(cKDTree(pos).query(observers,
+ distance_upper_bound=max_distance+np.sqrt(length2.max()))[0])
+ for base in range(0,len(points),chunk_size):
+ indices = np.flatnonzero(supported[base:base+chunk_size])+base
+ if not len(indices):
+ continue
+ obs = observers[indices]
+ residual = pos[:-1][None,:,:]-obs[:,None,:]
+ fraction = np.clip(-np.einsum("bsi,si->bs",residual,delta)/np.maximum(length2,1e-12),0,1)
+ dist2 = np.sum((residual+fraction[:,:,None]*delta[None,:,:])**2,axis=2)
+ # A zero-velocity segment or path endpoint is not evidence of a full
+ # flyover. Keep interior minima and deduplicate adjoining segments.
+ for j in range(len(obs)):
+ peaks = find_peaks(-dist2[j],plateau_size=1)[0]
+ if len(dist2[j]) > 2:
+ global_i = int(np.argmin(dist2[j]))
+ if 0 < global_i < len(dist2[j])-1:
+ peaks = np.unique(np.r_[peaks,global_i])
+ last_time = -np.inf
+ for k in peaks:
+ distance = np.sqrt(dist2[j,k])
+ when = t[k]+fraction[j,k]*(t[k+1]-t[k])
+ if distance > max_distance or when-last_time < step_s*1.1:
+ continue
+ last_time = when
+ rows.append({"point_id":int(points.iloc[indices[j]].point_id),"flight_id":track.id,
+ "emission_time":when,"receive_time":when+distance/c,
+ "distance_m":distance,
+ "speed_mps":np.linalg.norm(track.speed_vector(when))})
+ return pd.DataFrame(rows,columns=["point_id","flight_id","emission_time","receive_time","distance_m","speed_mps"])
+
+
+def filter_event(table, event, time_origin=None, time_tolerance=5.0):
+ speed, distance = event["speed_range_mps"],event["slant_range_m"]
+ keep = table.speed_mps.between(*speed) & table.distance_m.between(*distance)
+ if time_origin is not None:
+ keep &= np.abs(table.receive_time-(time_origin+event["cpa_receive_s"])) <= time_tolerance
+ return table.loc[keep]
+
+
+def pair_candidates(table, events, offset_tolerance_s=5.0, time_origin=None,
+ time_tolerance_s=5.0, silence=None):
+ filtered = [filter_event(table,event,time_origin,time_tolerance_s) for event in events]
+ if any(frame.empty for frame in filtered):
+ return [],{"per_event_survivors":[len(f) for f in filtered],"pairs_before_silence":0,"silence_rejected":0}
+ group = [dict(tuple(frame.groupby("point_id"))) for frame in filtered]
+ common = set.intersection(*(set(g) for g in group))
+ all_by_point = dict(tuple(table.groupby("point_id")))
+ candidates, before, rejected = [],0,0
+ for point_id in sorted(common):
+ for combination in product(*(list(g[point_id].to_dict("records")) for g in group)):
+ anchor = combination[0]["receive_time"]
+ if any(abs((row["receive_time"]-anchor)-(events[i]["cpa_receive_s"]-events[0]["cpa_receive_s"]))
+ > offset_tolerance_s for i,row in enumerate(combination[1:],1)):
+ continue
+ if len(combination)>1 and len({(r["flight_id"],round(r["emission_time"],1)) for r in combination})<len(combination):
+ continue
+ before += 1
+ if silence and len(combination)>1:
+ threshold = max(row["distance_m"] for row in combination)*silence.get("distance_multiplier",1.0)
+ margin = silence.get("edge_margin_s",60)
+ between = all_by_point[point_id]
+ between = between[(between.receive_time>anchor+margin)&
+ (between.receive_time<combination[-1]["receive_time"]-margin)&
+ (between.distance_m<=threshold)]
+ # Only the selected actual passes are excluded, not every future
+ # pass by an aircraft with the same flight ID.
+ if len(between):
+ rejected += 1
+ continue
+ candidates.append({"point_id":point_id,"passes":combination})
+ return candidates,{"per_event_survivors":[len(f) for f in filtered],
+ "pairs_before_silence":before,"silence_rejected":rejected,"survivors":len(candidates)}
+
+
+def event_score(track, observer, spectrum, ridge, weight, start_time, f0_bounds, mode, c=343.0,
+ frequency_step=0.2):
+ # The same receiver-clock time is used for all events. No per-event time fit.
+ times = spectrum.time
+ factor,_,_ = track.acoustic(start_time+times,observer,c)
+ valid = np.isfinite(factor)
+ if np.mean(valid)<0.95:
+ return -np.inf,np.nan
+ if mode=="ridge":
+ valid &= np.isfinite(ridge)
+ if np.sum(valid)<10:
+ return -np.inf,np.nan
+ w = np.maximum(np.asarray(weight)[valid],0.05)
+ f0 = np.clip(np.sum(w*factor[valid]*ridge[valid])/np.sum(w*factor[valid]**2),*f0_bounds)
+ rmse = np.sqrt(np.average((f0*factor[valid]-ridge[valid])**2,weights=w))
+ return -float(rmse),float(f0)
+ frequencies = np.linspace(*f0_bounds,max(3,int(np.ceil((f0_bounds[1]-f0_bounds[0])/frequency_step))+1))
+ predicted = frequencies[:,None]*factor[None,:]
+ contrast = spectrum.sample(times[None,:],predicted)
+ # Fixed support: candidates do not gain points by leaving the frequency band.
+ scores = np.where(np.mean(np.isfinite(contrast),axis=1)>=0.95,
+ np.mean(np.nan_to_num(contrast,nan=-4.0),axis=1),-np.inf)
+ best = np.argmax(scores)
+ return float(scores[best]),float(frequencies[best])
+
+
+def score_candidate(candidate, point, tracks, events, measurements, mode="brightness",
+ time_origin=None, time_sweep_s=5.0, time_step_s=0.5, c=343.0):
+ observer = ecef(point.lat,point.lon,point.elev_m)
+ # Derive one recording start from the first event; all other events retain
+ # their true absolute geometry/time. This implements the locked offset.
+ anchor = time_origin if time_origin is not None else candidate["passes"][0]["receive_time"]-events[0]["cpa_receive_s"]
+ shifts = np.linspace(-time_sweep_s,time_sweep_s,max(1,int(np.ceil(2*time_sweep_s/time_step_s)))+1)
+ best = {"score":-np.inf}
+ for shift in shifts:
+ scores,f0s = [],[]
+ for event,measurement,flyover in zip(events,measurements,candidate["passes"]):
+ spec,ridge,weight,_ = measurement
+ score,f0 = event_score(tracks[flyover["flight_id"]],observer,spec,ridge,weight,
+ anchor+shift,event["f0_range_hz"],mode,c,event.get("frequency_step_hz",0.2))
+ scores.append(score)
+ f0s.append(f0)
+ total = float(np.sum(scores))
+ if total>best["score"]:
+ best = {"score":total,"event_scores":scores,"f0_hz":f0s,
+ "recording_start_time_s":float(anchor+shift),"time_adjustment_s":float(shift)}
+ return dict(best,point_id=int(point.point_id),lat=float(point.lat),lon=float(point.lon),elev_m=float(point.elev_m),
+ x=float(point.x),y=float(point.y),flight_ids=[p["flight_id"] for p in candidate["passes"]])
+
+
+def rank_candidates(candidates, points, tracks, events, measurements, **kwargs):
+ lookup = {row.point_id:row for row in points.itertuples()}
+ track_lookup = {track.id:track for track in tracks}
+ result = []
+ for i,candidate in enumerate(candidates):
+ row = score_candidate(candidate,lookup[candidate["point_id"]],track_lookup,events,measurements,**kwargs)
+ if np.isfinite(row["score"]):
+ result.append(row)
+ if i and i%100==0:
+ print(f"Scored {i}/{len(candidates)} candidates",flush=True)
+ return sorted(result,key=lambda r:r["score"],reverse=True)
diff --git a/src/aircraft_geoloc/terrain.py b/src/aircraft_geoloc/terrain.py
new file mode 100644
index 0000000..25fa53f
--- /dev/null
+++ b/src/aircraft_geoloc/terrain.py
@@ -0,0 +1,99 @@
+"""Terrain sampling and common projected grids."""
+from pathlib import Path
+
+import numpy as np
+from pyproj import Transformer
+
+
+class Terrain:
+ def __init__(self, paths=None, constant_m=None, geoid_path=None):
+ import rasterio
+ self.rasters = [rasterio.open(p) for p in (paths or [])]
+ self.constant = constant_m
+ self.geoid = Terrain([geoid_path]) if geoid_path else None
+ if not self.rasters and constant_m is None:
+ raise ValueError("Supply DEM raster paths or an explicit constant ground elevation")
+
+ def sample(self, lat, lon):
+ lat, lon = np.broadcast_arrays(lat, lon)
+ elevation = np.full(lat.shape, np.nan)
+ for raster in self.rasters:
+ transform = Transformer.from_crs("EPSG:4326", raster.crs, always_xy=True)
+ x, y = transform.transform(lon.ravel(), lat.ravel())
+ values = np.ma.asarray(list(raster.sample(zip(x, y), masked=True)))[:, 0]
+ valid = ~np.ma.getmaskarray(values)
+ flat = elevation.ravel()
+ flat[valid] = np.asarray(values)[valid]
+ if self.constant is not None:
+ elevation[~np.isfinite(elevation)] = self.constant
+ if not np.all(np.isfinite(elevation)):
+ raise ValueError(f"DEM coverage missing for {np.sum(~np.isfinite(elevation))} candidate points")
+ if self.geoid:
+ elevation += self.geoid.sample(lat,lon)
+ return elevation
+
+
+def corridor_grid(tracks, events, spacing_m, terrain, crs="EPSG:5070", bounds=None, time_origin=None):
+ """Only materialize grid cells near plausible aircraft segments.
+
+ Coordinates use one shared CRS and grid origin, so overlapping flight corridors
+ deduplicate. There is no recording-position prior hidden in grid construction.
+ """
+ forward = Transformer.from_crs("EPSG:4326", crs, always_xy=True)
+ inverse = Transformer.from_crs(crs, "EPSG:4326", always_xy=True)
+ cells = []
+ for track in tracks:
+ for event in events:
+ lo_v, hi_v = event["speed_range_mps"]
+ radius = event["slant_range_m"][1]
+ # Sampling by travelled distance prevents a long path from producing
+ # a huge empty bounding rectangle. Expand disks for the anchor gap.
+ anchor_step = max(1.0, radius / 3 / max(hi_v, 1))
+ t = np.arange(track.time[0], track.time[-1], anchor_step)
+ if time_origin is not None:
+ lo = time_origin + event["start_s"] - radius / event.get("sound_speed_mps", 343) - 10
+ hi = time_origin + event["end_s"] + 10
+ t = t[(t >= lo) & (t <= hi)]
+ if not len(t):
+ continue
+ speed = np.linalg.norm(track.speed_vector(t), axis=1)
+ t = t[(speed >= lo_v) & (speed <= hi_v)]
+ if not len(t):
+ continue
+ lat = np.interp(t, track.time, track.lat)
+ lon = np.interp(t, track.time, track.lon)
+ x, y = forward.transform(lon, lat)
+ anchors = np.unique(np.round(np.column_stack((x, y)) / spacing_m).astype(np.int64), axis=0)
+ # EPSG:5070 grid scale is close to unity over CONUS; 10% padding
+ # plus an anchor gap protects corridor coverage under distortion.
+ pad = radius * 1.45 + spacing_m
+ size = int(np.ceil(pad / spacing_m))
+ dx, dy = np.meshgrid(np.arange(-size, size+1), np.arange(-size,size+1))
+ offsets = np.column_stack((dx.ravel(), dy.ravel()))
+ offsets = offsets[np.linalg.norm(offsets, axis=1) * spacing_m <= pad]
+ for anchor in anchors:
+ cells.append(anchor + offsets)
+ if not cells:
+ raise ValueError("No flight segments meet event speed/time bounds")
+ cells = np.unique(np.concatenate(cells), axis=0)
+ x, y = cells[:,0] * spacing_m, cells[:,1] * spacing_m
+ lon, lat = inverse.transform(x, y)
+ if bounds:
+ west, south, east, north = bounds
+ keep = (lon >= west) & (lon <= east) & (lat >= south) & (lat <= north)
+ x, y, lon, lat = (a[keep] for a in (x,y,lon,lat))
+ height = terrain.sample(lat,lon)
+ import pandas as pd
+ return pd.DataFrame({"point_id": np.arange(len(x)), "x":x, "y":y, "lat":lat, "lon":lon, "elev_m":height})
+
+
+def refine_grid(points, coarse_spacing, fine_spacing, terrain, crs="EPSG:5070"):
+ inverse = Transformer.from_crs(crs, "EPSG:4326", always_xy=True)
+ radius = int(np.ceil(coarse_spacing / fine_spacing))
+ dx, dy = np.meshgrid(np.arange(-radius,radius+1),np.arange(-radius,radius+1))
+ offsets = np.column_stack((dx.ravel(),dy.ravel())) * fine_spacing
+ coords = np.unique(np.concatenate([np.array([r.x,r.y])+offsets for r in points.itertuples()]),axis=0)
+ lon,lat = inverse.transform(coords[:,0],coords[:,1])
+ import pandas as pd
+ return pd.DataFrame({"point_id":np.arange(len(coords)),"x":coords[:,0],"y":coords[:,1],
+ "lat":lat,"lon":lon,"elev_m":terrain.sample(lat,lon)})
diff --git a/src/aircraft_geoloc/tracks.py b/src/aircraft_geoloc/tracks.py
new file mode 100644
index 0000000..a0b5824
--- /dev/null
+++ b/src/aircraft_geoloc/tracks.py
@@ -0,0 +1,130 @@
+"""Canonical CSV/Parquet and public ADS-B KML/trace importers."""
+import json
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+from .geometry import Track, velocity_ecef
+
+
+def unix_time(value):
+ if isinstance(value, (float, int, np.number)):
+ return float(value)
+ return pd.Timestamp(value).timestamp()
+
+
+def read_kml(path):
+ ns = {"k": "http://www.opengis.net/kml/2.2", "gx": "http://www.google.com/kml/ext/2.2"}
+ root = ET.parse(path).getroot()
+ rows = []
+ for placemark in root.findall(".//k:Placemark", ns):
+ name = placemark.findtext("k:name", default=Path(path).stem, namespaces=ns)
+ for trace in placemark.findall(".//gx:Track", ns):
+ timestamps = trace.findall("k:when", ns)
+ coords = trace.findall("gx:coord", ns)
+ if len(timestamps) != len(coords):
+ raise ValueError(f"{path}: KML timestamps and coordinates differ")
+ for t, coord in zip(timestamps, coords):
+ lon, lat, altitude = map(float, coord.text.split())
+ rows.append({"flight_id": name, "time_s": unix_time(t.text),
+ "lat": lat, "lon": lon, "alt_m": altitude})
+ return pd.DataFrame(rows)
+
+
+def read_adsblol_trace(path):
+ """tar1090 trace format; trace offsets are seconds, altitude feet, speed knots."""
+ import gzip
+ raw=Path(path).read_bytes()
+ d=json.loads(gzip.decompress(raw) if raw[:2]==b"\x1f\x8b" else raw)
+ return adsblol_frame(d)
+
+
+def adsblol_frame(d):
+ """Normalize readsb trace fields using the documented geometric-altitude slot.
+
+ Missing geometric samples use an interpolated geometric-minus-baro offset
+ only when this aircraft provides such measurements. A wholly barometric
+ trace remains explicitly labelled; it is not silently called geometric.
+ """
+ valid=[p for p in d["trace"] if isinstance(p[3],(int,float))]
+ offsets=[]
+ for p in valid:
+ geom=p[10] if len(p)>10 else None
+ if geom is not None and not (p[6]&8):
+ offsets.append((p[0],geom-p[3]))
+ rows = []
+ for p in valid:
+ metadata = p[8] if len(p) > 8 and isinstance(p[8], dict) else {}
+ geom=p[10] if len(p)>10 else None
+ if p[6]&8:
+ altitude,basis=p[3],"ellipsoidal"
+ elif geom is not None:
+ altitude,basis=geom,"ellipsoidal"
+ elif offsets:
+ altitude=p[3]+np.interp(p[0],*[np.array(offsets)[:,i] for i in [0,1]])
+ basis="ellipsoidal_interpolated"
+ else:
+ altitude,basis=p[3],"barometric"
+ speed=(p[4] or 0)*0.514444
+ heading=np.deg2rad(p[5] or 0)
+ rate=p[11] if len(p)>11 and p[11] is not None else p[7]
+ rows.append({"flight_id": d["icao"],
+ "time_s": d["timestamp"] + p[0], "lat": p[1], "lon": p[2],
+ "alt_m": altitude*0.3048,"speed_mps":speed,"heading_deg":p[5],
+ "east_mps":speed*np.sin(heading),"north_mps":speed*np.cos(heading),
+ "up_mps":(rate or 0)*0.00508,
+ "typecode":metadata.get("t",d.get("t","")),"altitude_basis":basis})
+ return pd.DataFrame(rows)
+
+
+def load_tracks(path, max_gap_s=30.0, type_database=None, bounds=None, time_range=None):
+ path = Path(path)
+ if path.suffix.lower() == ".kml":
+ df = read_kml(path)
+ elif path.suffix.lower() in (".json", ".gz"):
+ df = read_adsblol_trace(path)
+ elif path.suffix.lower() == ".parquet":
+ filters=[]
+ if bounds:
+ west,south,east,north=bounds
+ filters += [("lon",">=",west),("lon","<=",east),("lat",">=",south),("lat","<=",north)]
+ if time_range:
+ filters += [("time_s",">=",time_range[0]),("time_s","<=",time_range[1])]
+ df = pd.read_parquet(path,filters=filters or None)
+ else:
+ df = pd.read_csv(path)
+ required = {"time_s", "lat", "lon", "alt_m"}
+ if not required.issubset(df):
+ raise ValueError(f"{path}: required columns {sorted(required)} (SI units)")
+ if "flight_id" not in df:
+ df["flight_id"] = path.stem
+ df["time_s"] = df.time_s.map(unix_time)
+ types = {}
+ if type_database:
+ # ICAO doc8643-style CSV: designator and engine_type (Jet/Turboprop/Piston).
+ table = pd.read_csv(type_database).fillna("")
+ types = dict(zip(table.designator, table.engine_type.str.lower()))
+ tracks, rejected = [], []
+ for flight_id, group in df.groupby("flight_id", sort=False):
+ group = group.sort_values("time_s").drop_duplicates("time_s")
+ group = group.dropna(subset=list(required))
+ code = str(group.typecode.iloc[0]) if "typecode" in group else ""
+ if types.get(code, "") in ("jet", "j", "turbofan", "turbojet"):
+ rejected.append(str(flight_id))
+ continue
+ chunks = (group.time_s.diff() > max_gap_s).cumsum()
+ for index, (_, chunk) in enumerate(group.groupby(chunks)):
+ if len(chunk) < 3:
+ continue
+ v = None
+ if {"east_mps", "north_mps", "up_mps"}.issubset(chunk):
+ v = velocity_ecef(chunk.lat.to_numpy(), chunk.lon.to_numpy(),
+ chunk.east_mps.to_numpy(), chunk.north_mps.to_numpy(), chunk.up_mps.to_numpy())
+ identifier = str(flight_id) + (f":{index}" if chunks.max() else "")
+ tracks.append(Track(identifier, chunk.time_s.to_numpy(), chunk.lat.to_numpy(),
+ chunk.lon.to_numpy(), chunk.alt_m.to_numpy(), code, v))
+ return tracks, {"rows": len(df), "segments": len(tracks), "known_jets_excluded": rejected,
+ "altitude_basis_counts":df.altitude_basis.value_counts().to_dict() if "altitude_basis" in df else {},
+ "unknown_types_retained": True}
diff --git a/tests/test_audio.py b/tests/test_audio.py
new file mode 100644
index 0000000..68a9d33
--- /dev/null
+++ b/tests/test_audio.py
@@ -0,0 +1,24 @@
+import numpy as np
+import soundfile as sf
+
+from aircraft_geoloc.audio import measure
+from aircraft_geoloc.tracks import adsblol_frame
+
+
+def test_noise_does_not_force_a_detection(tmp_path):
+ p=tmp_path/"noise.wav"
+ sf.write(p,np.random.default_rng(791).normal(0,0.1,4000*45),4000)
+ *_,fit=measure(p,{"start_s":0,"end_s":45,"band_hz":[80,180]})
+ assert not fit["detected"]
+
+
+def test_geometric_altitude_slot_and_labelled_fallback():
+ trace={"icao":"abc123","timestamp":1000,"t":"C172","trace":[
+ [0,40,-100,3000,100,90,0,0,None,"adsb_icao",3100,0],
+ [1,40,-100,3000,100,90,0,0,None,"adsb_icao",None,0]]}
+ frame=adsblol_frame(trace)
+ assert np.allclose(frame.alt_m,3100*0.3048)
+ assert list(frame.altitude_basis)==["ellipsoidal","ellipsoidal_interpolated"]
+ trace["trace"]=[trace["trace"][1]]
+ frame=adsblol_frame(trace)
+ assert frame.altitude_basis.iloc[0]=="barometric"
diff --git a/tests/test_filters.py b/tests/test_filters.py
new file mode 100644
index 0000000..4e9ef14
--- /dev/null
+++ b/tests/test_filters.py
@@ -0,0 +1,39 @@
+import numpy as np
+import pandas as pd
+
+from aircraft_geoloc.search import pair_candidates
+from aircraft_geoloc.tracks import load_tracks
+
+
+def event(cpa):
+ return {"cpa_receive_s":cpa,"speed_range_mps":[60,100],"slant_range_m":[1000,3000]}
+
+
+def test_silence_and_locked_offset_filter():
+ rows=[]
+ for point in [0,1,2]:
+ for flight,when in [("a",100),("b",1020 if point!=2 else 1040)]:
+ rows.append({"point_id":point,"flight_id":flight,"receive_time":when,
+ "emission_time":when-5,"distance_m":2000,"speed_mps":80})
+ rows.append({"point_id":1,"flight_id":"extra","receive_time":600,
+ "emission_time":595,"distance_m":1800,"speed_mps":80})
+ candidates,counts=pair_candidates(pd.DataFrame(rows),[event(50),event(970)],silence={"edge_margin_s":60})
+ assert [c["point_id"] for c in candidates]==[0]
+ assert counts["pairs_before_silence"]==2
+ assert counts["silence_rejected"]==1
+
+
+def test_known_jets_only_are_excluded_and_gaps_are_not_interpolated(tmp_path):
+ rows=[]
+ for flight,code in [("jet","A320"),("prop","C172"),("unknown","ZZZZ")]:
+ for t in [0,1,2,100,101,102]:
+ rows.append({"flight_id":flight,"time_s":t,"lat":40+t/1000,"lon":-100,
+ "alt_m":1000,"typecode":code})
+ p=tmp_path/"tracks.csv";pd.DataFrame(rows).to_csv(p,index=False)
+ db=tmp_path/"types.csv"
+ pd.DataFrame({"designator":["A320","C172"],"engine_type":["Jet","Piston"]}).to_csv(db,index=False)
+ tracks,report=load_tracks(p,type_database=db)
+ assert len(tracks)==4
+ assert report["known_jets_excluded"]==["jet"]
+ assert {t.id.split(":")[0] for t in tracks}=={"prop","unknown"}
+ assert all(np.isnan(t.position(50)).all() for t in tracks)
diff --git a/tests/test_locked_scoring.py b/tests/test_locked_scoring.py
new file mode 100644
index 0000000..171e5bd
--- /dev/null
+++ b/tests/test_locked_scoring.py
@@ -0,0 +1,30 @@
+from types import SimpleNamespace
+
+import numpy as np
+
+from aircraft_geoloc.audio import Spectrum
+from aircraft_geoloc.search import score_candidate
+
+
+class Flyover:
+ def __init__(self,center):self.center=center
+ def acoustic(self,t,observer,c):
+ factor=1.1-0.25*np.tanh((t-self.center)/8)
+ return factor,np.asarray(t),np.ones_like(t)
+
+
+def test_second_event_cannot_get_its_own_time_adjustment():
+ point=SimpleNamespace(point_id=0,lat=40,lon=-100,elev_m=0,x=0,y=0)
+ events=[];measurements=[]
+ for center in [30,950]:
+ t=np.arange(center-25,center+25,0.5)
+ spec=Spectrum(t,np.arange(80,161),np.zeros((81,len(t))),np.zeros((81,len(t))))
+ ridge=120*Flyover(center).acoustic(t,None,343)[0]
+ measurements.append((spec,ridge,np.ones(len(t)),{}))
+ events.append({"cpa_receive_s":center,"f0_range_hz":[119.9,120.1]})
+ candidate={"passes":[{"flight_id":"a","receive_time":30},{"flight_id":"b","receive_time":950}]}
+ kwargs=dict(mode="ridge",time_origin=0,time_sweep_s=10,time_step_s=0.5)
+ correct=score_candidate(candidate,point,{"a":Flyover(30),"b":Flyover(950)},events,measurements,**kwargs)
+ wrong=score_candidate(candidate,point,{"a":Flyover(30),"b":Flyover(958)},events,measurements,**kwargs)
+ assert abs(correct["score"])<1e-8
+ assert wrong["score"] < -5
diff --git a/tests/test_physics.py b/tests/test_physics.py
new file mode 100644
index 0000000..2d5ef21
--- /dev/null
+++ b/tests/test_physics.py
@@ -0,0 +1,35 @@
+import numpy as np
+from numpy.testing import assert_allclose
+from pyproj import Transformer
+
+from aircraft_geoloc.geometry import Track,ecef,straight_doppler
+
+
+def straight_track(epoch=0.0):
+ observer=ecef(40,-100,100)
+ # Constant Cartesian source velocity is independent of the geodetic import.
+ t=np.arange(-100,101,1.0)
+ xyz=observer+np.column_stack((80*t,np.full(len(t),1300),np.full(len(t),700)))
+ inverse=Transformer.from_crs("EPSG:4978","EPSG:4979",always_xy=True)
+ lon,lat,h=inverse.transform(*xyz.T)
+ track=Track("straight",t+epoch,lat,lon,h,velocity=np.tile([80,0,0],(len(t),1)))
+ return track,observer,np.hypot(1300,700)
+
+
+def test_retarded_time_against_closed_form_and_large_epoch():
+ for epoch in [0.0,1_790_000_000.0]:
+ track,observer,slant=straight_track(epoch)
+ receive=np.linspace(-65,65,501)+epoch
+ factor,emission,distance=track.acoustic(receive,observer)
+ assert_allclose(emission+distance/343,receive,atol=3e-7,rtol=0)
+ expected=straight_doppler(receive-epoch,120,80,slant,slant/343)
+ assert_allclose(120*factor,expected,atol=3e-6,rtol=0)
+
+
+def test_cpa_and_no_extrapolation():
+ track,observer,slant=straight_track(1_790_000_000)
+ cpa=track.closest_approaches(observer)[0]
+ assert abs(cpa["emission_time"]-1_790_000_000)<0.001
+ assert abs(cpa["distance_m"]-slant)<0.001
+ factor,_,_=track.acoustic(np.array([1_789_999_800.0,1_790_000_200.0]),observer)
+ assert np.all(np.isnan(factor))