You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

182 lines
9.7 KiB

#!/usr/bin/env python3
"""End-to-end frame simulation: preamble + header + MAC + payload.
Every trial builds a full frame (licensed profile, source callsign, random
body), passes it through the impairment channel, and runs the two-stage
receiver. Failures are split by where they happened:
no-sync preamble not detected, or locked to the wrong position
hdr-fail header did not decode (or decoded to an unsupported mode)
pay-fail header fine, payload LDPC/CRC failed
ok payload and MAC delivered intact
Channel options (on top of the default impairments):
--fading rayleigh|rician --fd HZ --k-db DB flat fading, Doppler fd
--itf fm:25 --itf cw:-40 --sir DB [DB ...] interferers at kHz offsets,
swept over SIR (all equal)
--adc-bits 8 quantize like an RTL-SDR
--lo-offset HZ transverter-style LO error
--no-excise receiver without excision
--tracker legacy v0.4 pilot tracker, for comparison
--noncoherent index-only payload (mode 1)
The "x RT" column is processing speed: frame airtime divided by the mean
time receive_frame took per trial, on one core (>1 = faster than real time).
Usage:
./sim_frame.py --sf 7 --snr -13 -12 -11 -10 --trials 60
./sim_frame.py --sf 12 --snr -25 -24 -23 --trials 15 --bytes 24
./sim_frame.py --sf 7 --snr -12 -11 -10 --trials 400 --jobs 4
./sim_frame.py --sf 7 --snr 0 --itf fm:25 --sir -10 -15 -20 --trials 200
./sim_frame.py --sf 7 --snr -10 -5 0 5 10 --fading rayleigh --trials 400
./sim_frame.py --sf 7 --snr -5 --itf fm:25 --sir -30 -40 -50 --adc-bits 8
"""
import parallel # before numpy: one BLAS thread per worker
import argparse, time
from functools import partial
import numpy as np
from phy import PhyParams, payload_layout
from channel import ChannelConfig, Interferer, apply_channel
from frame import build_frame, receive_frame, LICENSED
def impaired_cfg(rng, p, snr_db, clean=False, chan=None):
if clean:
cfg = ChannelConfig(snr_db=snr_db, delay_chips=rng.uniform(0, p.M),
phase=rng.uniform(0, 2 * np.pi))
else:
cfg = ChannelConfig(
snr_db=snr_db, ppm=rng.uniform(-50, 50), delay_chips=rng.uniform(0, p.M),
phase=rng.uniform(0, 2 * np.pi),
dc=0.3 * (rng.standard_normal() + 1j * rng.standard_normal()),
iq_gain_db=0.5, iq_phase_deg=3.0)
if chan:
cfg.fading = chan.get("fading", "none")
cfg.fd_hz = chan.get("fd_hz", 0.0)
cfg.k_db = chan.get("k_db", 6.0)
cfg.interferers = [Interferer(kind=k, offset_hz=f, sir_db=chan["sir_db"])
for k, f in chan.get("itf", [])]
cfg.adc_bits = chan.get("adc_bits", 0)
cfg.lo_offset_hz = chan.get("lo_offset_hz", 0.0)
d = chan.get("drift_hz_per_s", 0.0)
if d: # only draw when used: other runs stay identical
cfg.drift_hz_per_s = d * (1 if rng.random() < 0.5 else -1)
return cfg
STAGES = ("no_sync", "header_fail", "payload_fail", "ok")
def _trial(rng, p, snr_db, n_bytes, iterative, clean, chan=None, excise=True,
tracker="adaptive", coherent=True):
body = rng.bytes(n_bytes)
iq, meta = build_frame(p, body, profile=LICENSED, src="W1AW", coherent=coherent)
y, truth = apply_channel(iq, p, impaired_cfg(rng, p, snr_db, clean, chan), rng)
t0 = time.perf_counter()
res = receive_frame(y, p, iterative=iterative, excise=excise, tracker=tracker)
dt = time.perf_counter() - t0
stage = res.stage
if stage != "ok" and res.sync is not None and \
abs(res.sync.tau0 - truth["frame_start_rx"] / p.osr) > 0.5:
stage = "no_sync" # failed because it locked to the wrong place
if stage == "ok" and (res.mac.body != body or res.mac.src != "W1AW"):
stage = "payload_fail" # would be an undetected error
return STAGES.index(stage), dt, len(iq) / p.fs
def run_point(p, snr_db, trials, n_bytes, seed, iterative=True, clean=False, jobs=1,
chan=None, excise=True, tracker="adaptive", coherent=True):
fn = partial(_trial, p=p, snr_db=snr_db, n_bytes=n_bytes, iterative=iterative,
clean=clean, chan=chan, excise=excise, tracker=tracker, coherent=coherent)
res = parallel.run_trials(fn, trials, seed, jobs)
r = np.bincount([x[0] for x in res], minlength=len(STAGES))
out = {k: v / trials for k, v in zip(STAGES, r)}
dts = np.array([x[1] for x in res])
out["rt"] = float(np.mean([x[2] for x in res]) / dts.mean()) # x real time, mean
out["rt_worst"] = float(res[0][2] / dts.max())
return out
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--sf", type=int, nargs="+", default=[7])
ap.add_argument("--snr", type=float, nargs="+", default=[-13, -12, -11, -10])
ap.add_argument("--trials", type=int, default=50)
ap.add_argument("--bytes", type=int, default=24, help="MAC body bytes")
ap.add_argument("--osr", type=int, default=2)
ap.add_argument("--bw", type=float, default=125e3, help="chirp bandwidth, Hz")
ap.add_argument("--preamble", type=int, default=8, help="preamble up-chirps")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--clean", action="store_true", help="AWGN + delay + phase only")
ap.add_argument("--no-id", action="store_true", help="disable iterative demapping")
ap.add_argument("--jobs", type=int, default=parallel.default_jobs(),
help="worker processes (default: all cores)")
ap.add_argument("--fading", choices=["none", "rayleigh", "rician"], default="none")
ap.add_argument("--fd", type=float, default=0.0, help="max Doppler, Hz (0 = block)")
ap.add_argument("--k-db", type=float, default=6.0, help="Rician K factor, dB")
ap.add_argument("--itf", action="append", default=[],
help="interferer KIND:OFFSET_KHZ, KIND = cw or fm (repeatable)")
ap.add_argument("--sir", type=float, nargs="+", default=[0.0],
help="signal-to-interference ratio(s), dB, per interferer")
ap.add_argument("--lo-offset", type=float, default=0.0,
help="carrier offset (Hz) with no matching clock error, e.g. a transverter LO")
ap.add_argument("--drift", type=float, default=0.0,
help="carrier drift, Hz/s, random sign per trial (oscillator warming up)")
ap.add_argument("--adc-bits", type=int, default=0,
help="quantize I/Q to this many bits (RTL-SDR: 8); 0 = off")
ap.add_argument("--no-excise", action="store_true",
help="disable narrowband interference excision")
ap.add_argument("--noncoherent", action="store_true",
help="index-only payload (mode 1): no QPSK bits, no carrier phase needed")
ap.add_argument("--tracker", choices=["adaptive", "legacy"], default="adaptive",
help="pilot channel tracker (legacy = v0.4 phase-only fit)")
a = ap.parse_args()
itf = []
for spec in a.itf:
kind, off = spec.split(":")
itf.append((kind, float(off) * 1e3))
sirs = a.sir if itf else [None]
desc = []
if a.fading != "none":
desc.append(f"{a.fading} fading, fd {a.fd:g} Hz" +
(f", K {a.k_db:g} dB" if a.fading == "rician" else ""))
if itf:
desc.append("interferers " + ", ".join(f"{k} at {f / 1e3:+g} kHz" for k, f in itf))
if desc:
print("channel: " + "; ".join(desc))
if a.lo_offset:
print(f"front end: {a.lo_offset:+g} Hz LO offset without clock error "
f"(receiver would infer {a.lo_offset / 223.58e6 * 1e6:+.1f} ppm)")
if a.drift:
print(f"front end: carrier drifting {a.drift:g} Hz/s (random sign)")
if a.adc_bits:
desc_adc = f"{a.adc_bits}-bit ADC, AGC 12 dB back-off"
print("front end: " + desc_adc)
if a.no_excise:
print("receiver: interference excision off")
if a.noncoherent:
print("payload: non-coherent (index only)")
if a.tracker != "adaptive":
print(f"receiver: {a.tracker} channel tracker")
for sf in a.sf:
p = PhyParams(sf=sf, bw=a.bw, osr=a.osr, n_preamble=a.preamble)
_, meta = build_frame(p, b"\0" * a.bytes, src="W1AW", coherent=not a.noncoherent)
slots = len(payload_layout(meta["n_hdr"] + meta["n_pay"], p.pilot_every)[0])
air = (p.payload_start + slots * p.M) / p.bw
print(f"SF{sf}: {a.bytes} B body + 7 B MAC, header {meta['n_hdr']} sym, "
f"payload {meta['n_pay']} sym, ~{air:.2f} s on air at {p.bw / 1e3:.0f} kHz")
print(f"{'SNR':>6} " + (f"{'SIR':>6} " if itf else "") +
f"{'no-sync':>8} {'hdr-fail':>9} {'pay-fail':>9} {'ok':>6} {'x RT':>6} {'worst':>6}")
for snr in a.snr:
for sir in sirs:
chan = dict(fading=a.fading, fd_hz=a.fd, k_db=a.k_db, itf=itf, sir_db=sir,
adc_bits=a.adc_bits, lo_offset_hz=a.lo_offset,
drift_hz_per_s=a.drift)
t0 = time.time()
r = run_point(p, snr, a.trials, a.bytes, a.seed, not a.no_id, a.clean,
a.jobs, chan, not a.no_excise, a.tracker, not a.noncoherent)
print(f"{snr:>6.1f} " + (f"{sir:>6.1f} " if itf else "") +
f"{r['no_sync']:>8.3f} {r['header_fail']:>9.3f} "
f"{r['payload_fail']:>9.3f} {r['ok']:>6.3f} {r['rt']:>6.1f} "
f"{r['rt_worst']:>6.1f} "
f"({time.time() - t0:.1f}s)", flush=True)