"""Channel / front-end impairment simulator. Models, in order: fractional delay + sample-clock error (resampling), flat fading, CFO and carrier phase, narrowband interferers, IQ imbalance, DC offset, AWGN. Fading: flat Rayleigh or Rician with maximum Doppler ``fd_hz``, generated as a sum of 32 sinusoids with random arrival angles (Clarke/Jakes spectrum), unit mean power. ``fd_hz = 0`` gives block fading: one random gain per frame, the case for fixed stations whose channel changes over seconds or minutes. ADC: with ``adc_bits`` > 0 the received samples (signal + interference + noise) are quantized to that many bits per I/Q rail, with the gain set by an ideal AGC so full scale sits ``adc_backoff_db`` above the total RMS level. An RTL-SDR has 8 bits; a strong interferer sets the gain and the quantization noise it leaves behind is spread across the band, where excision can't reach. Interferers are specified at the receiver: ``offset_hz`` relative to the RX center frequency, ``sir_db`` = desired signal power over interferer power. "cw" is an unmodulated carrier; "fm" is narrowband FM (voice-band noise, 300-3000 Hz, ``dev_hz`` RMS deviation), like a repeater or simplex user. Clock model: TX and RX each derive LO *and* ADC/DAC clock from one crystal. With relative error ``ppm`` the RX sees a carrier offset of ppm*fc and its sample grid is stretched by (1 + ppm*1e-6) relative to the TX grid. ``lo_offset_hz`` adds a carrier offset with *no* matching clock error, as from a transverter or up/down-converter with its own LO, or a dongle whose tuner and ADC run from different crystals. ``drift_hz_per_s`` makes the carrier offset change linearly with time (an oscillator warming up), starting from zero at the first sample. SNR convention: signal power per sample = 1 (constant-envelope chirp); SNR is measured in the signal bandwidth ``bw`` (what LoRa quotes, e.g. -20 dB @ SF12). """ from dataclasses import dataclass, field import numpy as np from dsp import resample_at @dataclass class ChannelConfig: snr_db: float = 0.0 ppm: float = 0.0 # shared-crystal mismatch TX vs RX lo_offset_hz: float = 0.0 # extra carrier offset, no clock error drift_hz_per_s: float = 0.0 # carrier offset changing linearly in time delay_chips: float = 0.0 # extra frame delay (fractional ok) pre_pad_chips: int = 300 # noise-only lead-in (chips) post_pad_chips: int = 300 phase: float = 0.0 # carrier phase (rad) dc: complex = 0j # DC offset, linear amplitude (signal rms = 1) iq_gain_db: float = 0.0 iq_phase_deg: float = 0.0 fading: str = "none" # "none" | "rayleigh" | "rician" fd_hz: float = 0.0 # maximum Doppler frequency k_db: float = 6.0 # Rician K factor (LOS / scattered power) interferers: list = field(default_factory=list) # of Interferer adc_bits: int = 0 # 0 = no quantization adc_backoff_db: float = 12.0 # full scale above total RMS seed: int = 0 @dataclass class Interferer: kind: str = "cw" # "cw" | "fm" offset_hz: float = 20e3 sir_db: float = 0.0 dev_hz: float = 2.0e3 # FM: RMS deviation (NFM: ~5 kHz peak) def fading_gain(n_samp, fs, kind, fd_hz, k_db, rng, n_sin=32): """Complex flat-fading gain per sample, E|g|^2 = 1.""" t = np.arange(n_samp) / fs alpha = rng.uniform(0, 2 * np.pi, n_sin) phi = rng.uniform(0, 2 * np.pi, n_sin) w = 2 * np.pi * fd_hz * np.cos(alpha) g = np.exp(1j * (np.outer(t, w) + phi)).sum(axis=1) / np.sqrt(n_sin) \ if fd_hz > 0 else np.full(n_samp, np.exp(1j * phi).sum() / np.sqrt(n_sin)) if kind == "rician": K = 10 ** (k_db / 10) a0, p0 = rng.uniform(0, 2 * np.pi), rng.uniform(0, 2 * np.pi) los = np.exp(1j * (2 * np.pi * fd_hz * np.cos(a0) * t + p0)) g = np.sqrt(K / (K + 1)) * los + np.sqrt(1 / (K + 1)) * g return g def interferer_wave(n_samp, fs, itf: Interferer, rng): """Unit-power interferer, then scaled by the caller.""" t = np.arange(n_samp) / fs ph0 = rng.uniform(0, 2 * np.pi) if itf.kind == "cw": return np.exp(1j * (2 * np.pi * itf.offset_hz * t + ph0)) if itf.kind == "fm": # voice-band modulating noise via FFT shaping, unit RMS m = np.fft.fft(rng.standard_normal(n_samp)) f = np.abs(np.fft.fftfreq(n_samp, 1 / fs)) m[(f < 300) | (f > 3000)] = 0 m = np.real(np.fft.ifft(m)) m /= np.sqrt(np.mean(m * m)) + 1e-30 inst_f = itf.offset_hz + itf.dev_hz * m return np.exp(1j * (2 * np.pi * np.cumsum(inst_f) / fs + ph0)) raise ValueError(f"unknown interferer kind {itf.kind!r}") def apply_channel(tx, p, cfg: ChannelConfig, rng=None): rng = rng or np.random.default_rng(cfg.seed) osr = p.osr pad0 = int(cfg.pre_pad_chips * osr) # tail must also absorb the frame delay and clock stretch pad1 = int((cfg.post_pad_chips + cfg.delay_chips + 16) * osr + abs(cfg.ppm) * 1e-6 * len(tx)) + 1 padded = np.concatenate([np.zeros(pad0, complex), tx, np.zeros(pad1, complex)]) N = len(padded) eps = cfg.ppm * 1e-6 n = np.arange(N, dtype=np.float64) delay = cfg.delay_chips * osr pos = pad0 + (1.0 + eps) * (n - pad0 - delay) # where RX sample n looks in TX grid y = resample_at(padded, pos, cutoff=1.0) if cfg.fading != "none": y = y * fading_gain(N, p.fs, cfg.fading, cfg.fd_hz, cfg.k_db, rng) f_cfo = eps * p.fc + cfg.lo_offset_hz # Hz ts = n / p.fs y = y * np.exp(1j * (2 * np.pi * f_cfo * ts + np.pi * cfg.drift_hz_per_s * ts * ts + cfg.phase)) for itf in cfg.interferers: y = y + 10 ** (-itf.sir_db / 20) * interferer_wave(N, p.fs, itf, rng) if cfg.iq_gain_db or cfg.iq_phase_deg: g = 10 ** (cfg.iq_gain_db / 20) ph = np.deg2rad(cfg.iq_phase_deg) a = (1 + g * np.exp(-1j * ph)) / 2 b = (1 - g * np.exp(1j * ph)) / 2 y = a * y + b * np.conj(y) y = y + cfg.dc snr = 10 ** (cfg.snr_db / 10) sigma2 = osr / snr # noise power per sample noise = np.sqrt(sigma2 / 2) * (rng.standard_normal(N) + 1j * rng.standard_normal(N)) truth = dict(frame_start_rx=pad0 + delay, f_cfo_hz=f_cfo, eps=eps) y = y + noise if cfg.adc_bits: full = np.sqrt(np.mean(np.abs(y) ** 2) / 2) * 10 ** (cfg.adc_backoff_db / 20) step = 2 * full / 2 ** cfg.adc_bits q = lambda v: np.clip(np.round(v / step - 0.5) + 0.5, -2 ** (cfg.adc_bits - 1) + 0.5, 2 ** (cfg.adc_bits - 1) - 0.5) * step y = q(y.real) + 1j * q(y.imag) return y, truth