#!/usr/bin/env python3 """Turn a transmit recording into a simulated receiver capture. Models a Pluto-style transmitter and an RTL-SDR-style receiver as two radios with independent crystals: each crystal error scales that radio's LO *and* its sample clock. Then adds noise, a DC spike and 8-bit quantization. TX: tx_file.py output (SigMF, any rate), LO = core:frequency, crystal +tx-ppm RX: LO --rx-lo, rate --fs, crystal +rx-ppm, writes cu8 like rtl_sdr ./tools/sim_capture.py hello cap --snr -10 --tx-ppm 12 --rx-ppm -30 ./rx_file.py cap --snr is measured in the signal bandwidth (from the TX file's chirpmodem:bw). --lo-offset adds carrier offset with no clock error (a transverter LO). """ import os, sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) import argparse import numpy as np import iq_io from dsp import resample_at def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("tx", help="transmit recording (SigMF)") ap.add_argument("out", help="output capture base name") ap.add_argument("--fs", type=float, default=2.4e6, help="receiver sample rate") ap.add_argument("--rx-lo", type=float, help="receiver LO, Hz (default: signal - 250 kHz)") ap.add_argument("--snr", type=float, default=-5.0, help="SNR in the signal bandwidth, dB") ap.add_argument("--tx-ppm", type=float, default=10.0, help="transmitter crystal error") ap.add_argument("--rx-ppm", type=float, default=-35.0, help="receiver crystal error") ap.add_argument("--lo-offset", type=float, default=0.0, help="extra carrier offset with no clock error, Hz") ap.add_argument("--dc-db", type=float, default=0.0, help="DC spike power relative to total noise power, dB") ap.add_argument("--format", default="cu8", choices=["cu8", "ci8", "ci16_le", "cf32_le"]) ap.add_argument("--backoff-db", type=float, default=12.0, help="AGC: full scale above total RMS, dB") ap.add_argument("--lead", type=float, default=0.3, help="extra noise before, s") ap.add_argument("--seed", type=int, default=1) a = ap.parse_args() m = iq_io.read_sigmf_meta(a.tx) fs_tx, tx_lo, ext = m["fs"], m["fc"], m["ext"] bw = ext.get("bw", 125e3) sig_f = ext.get("signal_freq", tx_lo) rx_lo = a.rx_lo if a.rx_lo is not None else sig_f - 250e3 x = iq_io.read_raw(m["data_path"], m["fmt"]) anns = [an for an in m["meta"].get("annotations", []) if an.get("core:label", "").startswith("chirpmodem")] # frames only, not CW ID on = np.concatenate([x[an["core:sample_start"]:an["core:sample_start"] + an["core:sample_count"]] for an in anns]) if anns else x p_sig = float(np.mean(np.abs(on) ** 2)) ta, tb = a.tx_ppm * 1e-6, a.rx_ppm * 1e-6 # RX sample n is taken at t = n / (fs (1+tb)); TX sample k plays at k / (fs_tx (1+ta)) ratio = fs_tx * (1 + ta) / (a.fs * (1 + tb)) dfreq = (tx_lo * (1 + ta) + a.lo_offset - rx_lo * (1 + tb)) / (a.fs * (1 + tb)) n_lead = int(a.lead * a.fs) n_out = n_lead + int(len(x) / ratio) sigma2 = p_sig * a.fs / (bw * 10 ** (a.snr / 10)) dc = np.sqrt(sigma2 * 10 ** (a.dc_db / 10)) * np.exp(1j * 0.7) rms = np.sqrt(sigma2 + p_sig * len(on) / len(x) + abs(dc) ** 2) full = rms / np.sqrt(2) * 10 ** (a.backoff_db / 20) rng = np.random.default_rng(a.seed) meta_path, data_path = iq_io.sigmf_paths(a.out) open(data_path, "wb").close() cutoff = min(1.0, a.fs / fs_tx) clipped = 0 for s in range(0, n_out, 1 << 20): n = np.arange(s, min(n_out, s + (1 << 20))) y = resample_at(x, (n - n_lead) * ratio, cutoff=cutoff) y = y * np.exp(2j * np.pi * ((dfreq * n) % 1.0)) y = y + dc + np.sqrt(sigma2 / 2) * (rng.standard_normal(len(n)) + 1j * rng.standard_normal(len(n))) y = y / full clipped += int(np.sum((np.abs(y.real) > 1) | (np.abs(y.imag) > 1))) iq_io.write_raw(data_path, y, a.format, append=True) truth = dict(sim_snr_db=a.snr, sim_tx_ppm=a.tx_ppm, sim_rx_ppm=a.rx_ppm, sim_lo_offset=a.lo_offset, sim_expected_offset_hz=(sig_f * (1 + ta) + a.lo_offset) / (1 + tb) - sig_f) iq_io.write_sigmf_meta(a.out, a.format, a.fs, rx_lo, description=f"simulated capture of {os.path.basename(a.tx)}", extra=truth) print(f"wrote {meta_path} + {data_path}: {n_out} samples, {n_out / a.fs:.2f} s at " f"{a.fs / 1e6:g} MS/s ({a.format}), RX LO {rx_lo / 1e6:.6f} MHz") print(f" signal at {sig_f / 1e6:.6f} MHz nominal, {truth['sim_expected_offset_hz']:+.0f} Hz " f"offset as seen by the receiver; SNR {a.snr:+.1f} dB in {bw / 1e3:g} kHz; " f"{clipped} clipped samples") if __name__ == "__main__": main()