"""Bit-exact Python model of qpsk_tx.sv: Gray QPSK mapper, root-raised-cosine pulse shaping and an NCO mixer. Run it as a script to (re)write the two ROM files that the RTL reads: rrc_taps.hex pulse-shaping taps, 16-bit two's complement sine256.hex one sine cycle in 256 Q1.15 samples /Volumes/M2-Dev/conda/envs/toptech/bin/python qpsk_model.py """ from __future__ import annotations from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent SPS = 8 # samples per symbol (one sample per clock) SPAN = 6 # filter length in symbols NTAPS = SPAN * SPS + 1 ALPHA = 0.35 # roll-off factor (one of the DVB-S2 values) LUT_BITS = 8 # NCO table address width PHASE_BITS = 32 # NCO phase accumulator width Q15_MAX = 32767 # ---------------------------------------------------------------- mapping def gray_map(bits: int) -> tuple[int, int]: """Map two bits to a QPSK symbol (I, Q) in {-1, +1}. bits[1] (MSB) sets the sign of I and bits[0] (LSB) the sign of Q: 0 -> +1, 1 -> -1. Neighbouring points differ in one bit (Gray code). """ i = -1 if (bits >> 1) & 1 else 1 q = -1 if bits & 1 else 1 return i, q def gray_demap(i: float, q: float) -> int: """Hard decision: the sign of each axis gives one bit.""" return (int(i < 0) << 1) | int(q < 0) # ---------------------------------------------------------------- RRC filter def rrc_frequency_response(f: np.ndarray, alpha: float = ALPHA) -> np.ndarray: """Square-root raised-cosine magnitude H(f) for symbol period Ts = 1. Same piecewise definition as ETSI EN 302 307-1 clause 5.6, with the Nyquist frequency fN = 1 / (2 Ts) = 0.5. """ fn = 0.5 f = np.abs(f) h = np.zeros_like(f) h[f < fn * (1 - alpha)] = 1.0 band = (f >= fn * (1 - alpha)) & (f <= fn * (1 + alpha)) h[band] = np.sqrt(0.5 + 0.5 * np.sin(np.pi / (2 * fn) * (fn - f[band]) / alpha)) return h def rrc_taps_float(alpha: float = ALPHA, sps: int = SPS, span: int = SPAN) -> np.ndarray: """Impulse response sampled at t = k / sps, k = -span*sps/2 .. +span*sps/2. Computed as the inverse Fourier transform of H(f), a real and even function, so h(t) = 2 * integral_0^fmax H(f) cos(2 pi f t) df. """ t = np.arange(-(span * sps) // 2, (span * sps) // 2 + 1) / sps f = np.linspace(0.0, 0.5 * (1 + alpha), 20001) hf = rrc_frequency_response(f, alpha) integrand = hf[None, :] * np.cos(2 * np.pi * f[None, :] * t[:, None]) return 2.0 * np.trapezoid(integrand, f, axis=1) def worst_case_sum(taps: np.ndarray, sps: int = SPS) -> float: """Largest |output| of the filter when the input is +-1 every sps samples.""" return max(float(np.sum(np.abs(taps[p::sps]))) for p in range(sps)) def rrc_taps_int(alpha: float = ALPHA, sps: int = SPS, span: int = SPAN) -> np.ndarray: """Integer taps scaled so that the filter output always fits in Q1.15.""" h = rrc_taps_float(alpha, sps, span) taps = np.round(h * Q15_MAX / worst_case_sum(h, sps)).astype(np.int64) while worst_case_sum(taps, sps) > Q15_MAX: # rounding can add a few LSBs taps = np.trunc(taps * 0.9999).astype(np.int64) return taps def sine_table(bits: int = LUT_BITS) -> np.ndarray: n = 1 << bits return np.round(Q15_MAX * np.sin(2 * np.pi * np.arange(n) / n)).astype(np.int64) def write_hex(path: Path, values: np.ndarray) -> None: """One 16-bit two's complement word per line, no comments.""" path.write_text("".join(f"{int(v) & 0xFFFF:04x}\n" for v in values)) def read_hex(path: Path) -> np.ndarray: words = [int(w, 16) for w in path.read_text().split()] return np.array([w - 0x10000 if w & 0x8000 else w for w in words], dtype=np.int64) # ---------------------------------------------------------------- transmitter def tuning_word(f_carrier: float, f_clk: float) -> int: return round(f_carrier / f_clk * (1 << PHASE_BITS)) % (1 << PHASE_BITS) def symbol_impulses(valid: list[int], bits: list[int], sps: int = SPS) -> tuple[np.ndarray, np.ndarray]: """Filter inputs x[e] for clock edge e: the mapped symbol when a symbol is accepted (sym_valid high while the sample counter is 0), otherwise 0.""" n = len(valid) xi = np.zeros(n, dtype=np.int64) xq = np.zeros(n, dtype=np.int64) for e in range(n): if valid[e] and e % sps == 0: xi[e], xq[e] = gray_map(bits[e]) return xi, xq def tx_reference(valid: list[int], bits: list[int], tw: int, taps: np.ndarray | None = None) -> dict[str, np.ndarray]: """Register values of qpsk_tx.sv after each clock edge e = 0, 1, 2, ... Edge 0 is the first rising edge with rst low. i_bb[e] = conv(x_i, taps)[e - 1] s_out[e] = round((i_bb[e-3] * C(e-2) - q_bb[e-3] * S(e-2)) / 2**16) where C(m) and S(m) are the cosine and sine table entries addressed by the top LUT_BITS bits of the phase m * tw. """ taps = rrc_taps_int() if taps is None else taps xi, xq = symbol_impulses(valid, bits) n = len(valid) ci = np.convolve(xi, taps)[:n] cq = np.convolve(xq, taps)[:n] i_bb = np.concatenate(([0], ci[:-1])) q_bb = np.concatenate(([0], cq[:-1])) table = sine_table() mask = (1 << PHASE_BITS) - 1 shift = PHASE_BITS - LUT_BITS quarter = 1 << (LUT_BITS - 2) s_out = np.zeros(n, dtype=np.int64) for e in range(4, n): m = e - 2 addr = ((m * tw) & mask) >> shift c = int(table[(addr + quarter) % len(table)]) s = int(table[addr]) acc = int(i_bb[e - 3]) * c - int(q_bb[e - 3]) * s s_out[e] = (acc + (1 << 15)) >> 16 # round half up, then floor return {"i_bb": i_bb, "q_bb": q_bb, "s_out": s_out} # ---------------------------------------------------------------- receiver def coherent_receiver(s_out: np.ndarray, tw: int, phase_offset: int = 2) -> tuple[np.ndarray, np.ndarray]: """Ideal coherent receiver for tx_reference() output, as a float model. Mixes s_out back to baseband with the same NCO phase (the transmitter's sample s_out[e] used phase index e - phase_offset), then applies the matched filter (the same RRC taps). Returns the matched-filter outputs. No noise, no timing or carrier recovery: the receiver knows both. """ n = len(s_out) m = np.arange(n) - phase_offset theta = 2 * np.pi * (((m * tw) & ((1 << PHASE_BITS) - 1)) >> (PHASE_BITS - LUT_BITS)) / (1 << LUT_BITS) r_i = 2.0 * s_out * np.cos(theta) r_q = -2.0 * s_out * np.sin(theta) h = rrc_taps_float() return np.convolve(r_i, h)[:n], np.convolve(r_q, h)[:n] if __name__ == "__main__": write_hex(HERE / "rrc_taps.hex", rrc_taps_int()) write_hex(HERE / "sine256.hex", sine_table()) print(f"wrote rrc_taps.hex ({NTAPS} taps) and sine256.hex ({1 << LUT_BITS} words)")