"""Fixed-point reference model for fir_transposed.sv. Coefficient design (scipy.signal.firwin), quantisation to Q1.15, and a bit-exact model of the filter output: full-precision integer convolution, round half up at bit 14, arithmetic shift right by 15, saturate to 16 bits. Run standalone to print the default coefficients as a SystemVerilog literal: python fir_model.py """ from __future__ import annotations import numpy as np from scipy import signal FS_HZ = 48_000.0 # example sample rate CUTOFF_HZ = 6_000.0 # example -6 dB cutoff of the windowed-sinc design NTAPS = 31 CW = 16 # coefficient width, Q1.15 DW = 16 # sample width, Q1.15 FRAC = 15 # fractional bits of coefficients (and of the output) def design_lowpass(ntaps: int = NTAPS, cutoff_hz: float = CUTOFF_HZ, fs_hz: float = FS_HZ) -> np.ndarray: """Floating-point low-pass coefficients (Hamming window, the firwin default).""" return signal.firwin(ntaps, cutoff_hz, fs=fs_hz) def quantise(h: np.ndarray, frac_bits: int = FRAC, width: int = CW) -> np.ndarray: """Round to the nearest integer in Q(width-frac_bits).frac_bits and saturate.""" q = np.round(np.asarray(h) * (1 << frac_bits)).astype(np.int64) lo, hi = -(1 << (width - 1)), (1 << (width - 1)) - 1 return np.clip(q, lo, hi) def acc_width(ntaps: int, dw: int = DW, cw: int = CW) -> int: """Accumulator width used by the RTL: product width plus ceil(log2(ntaps)) guard bits.""" return dw + cw + int(np.ceil(np.log2(ntaps))) def fir_full(x: np.ndarray, h_q: np.ndarray) -> np.ndarray: """Exact integer convolution y[n] = sum_k h[k] x[n-k], zero initial state.""" x = np.asarray(x, dtype=np.int64) h_q = np.asarray(h_q, dtype=np.int64) return np.convolve(x, h_q)[: len(x)] def round_sat(acc: np.ndarray, shift: int = FRAC, width: int = 16) -> np.ndarray: """Round half up (add 2^(shift-1)), arithmetic shift right, saturate to width bits.""" acc = np.asarray(acc, dtype=np.int64) y = (acc + (1 << (shift - 1))) >> shift # numpy >> on int64 is arithmetic (floor) lo, hi = -(1 << (width - 1)), (1 << (width - 1)) - 1 return np.clip(y, lo, hi) def fir_q15(x: np.ndarray, h_q: np.ndarray) -> np.ndarray: """Bit-exact output sequence of fir_transposed.sv for input samples x.""" return round_sat(fir_full(x, h_q)) def sv_coef_literal(h_q: np.ndarray, cw: int = CW) -> str: """Pack coefficients into one hex literal, h[0] in the least significant bits.""" word = 0 for k, c in enumerate(h_q): word |= (int(c) & ((1 << cw) - 1)) << (k * cw) return f"{len(h_q) * cw}'h{word:0{len(h_q) * cw // 4}x}" if __name__ == "__main__": h_q = quantise(design_lowpass()) print("coefficients:", h_q.tolist()) print("sum |h| =", int(np.abs(h_q).sum()), "of", 1 << FRAC) print("accumulator width:", acc_width(NTAPS)) print(sv_coef_literal(h_q))