"""NumPy reference model for the HLS FIR kernel in fir_hls.cpp. Coefficient design (scipy.signal.firwin, Hamming window), quantisation to Q1.15 and a bit-exact model of the kernel: full-precision integer convolution, round half up at bit 14, arithmetic shift right by 15, saturate to 16 bits. Same arithmetic as the RTL filter in lesson 15. Run standalone to print the quantised coefficients: python fir_ref.py """ from __future__ import annotations import re from pathlib import Path import numpy as np from scipy import signal FS_HZ = 48_000.0 CUTOFF_HZ = 6_000.0 NTAPS = 31 FRAC = 15 def design_q15(ntaps: int = NTAPS, cutoff_hz: float = CUTOFF_HZ, fs_hz: float = FS_HZ) -> np.ndarray: """Low-pass coefficients rounded to Q1.15 integers.""" h = signal.firwin(ntaps, cutoff_hz, fs=fs_hz) return np.clip(np.round(h * (1 << FRAC)), -32768, 32767).astype(np.int64) def coef_from_cpp(path: Path) -> np.ndarray: """Read the COEF table from fir_hls.cpp.""" text = path.read_text() body = re.search(r"COEF\[NTAPS\]\s*=\s*\{([^}]*)\}", text) if body is None: raise ValueError(f"no COEF table in {path}") return np.array([int(v) for v in body.group(1).replace("\n", " ").split(",") if v.strip()], dtype=np.int64) def fir_q15(x: np.ndarray, h_q: np.ndarray) -> np.ndarray: """Bit-exact output of the kernel for input x, starting from zero state.""" acc = np.convolve(np.asarray(x, dtype=np.int64), np.asarray(h_q, dtype=np.int64))[: len(x)] y = (acc + (1 << (FRAC - 1))) >> FRAC # numpy >> on int64 is arithmetic return np.clip(y, -32768, 32767) if __name__ == "__main__": print(", ".join(str(int(v)) for v in design_q15()))