"""Tests for the HLS FIR kernel: compile fir_hls.cpp and its C++ testbench with clang++, run the C simulation, and compare the kernel against the NumPy model. Build output goes to a temporary directory. Run with: python -m pytest -q """ from __future__ import annotations import shutil import subprocess import tempfile from collections.abc import Iterator from pathlib import Path import numpy as np import pytest from fir_ref import FRAC, coef_from_cpp, design_q15, fir_q15 HERE = Path(__file__).resolve().parent # -Wno-unknown-pragmas: clang does not know the HLS pragmas. # -Wno-unused-label: the loop labels only name the loops for the HLS tool. CXXFLAGS = ["-std=c++17", "-Wall", "-Wextra", "-Werror", "-Wno-unknown-pragmas", "-Wno-unused-label"] pytestmark = pytest.mark.skipif(shutil.which("clang++") is None, reason="clang++ not installed") @pytest.fixture(scope="module") def tb_exe() -> Iterator[Path]: with tempfile.TemporaryDirectory() as tmp: exe = Path(tmp) / "tb_fir_hls" subprocess.run(["clang++", *CXXFLAGS, str(HERE / "fir_hls.cpp"), str(HERE / "tb_fir_hls.cpp"), "-o", str(exe)], check=True, capture_output=True, text=True) yield exe def run_kernel(exe: Path, x: np.ndarray) -> np.ndarray: with tempfile.TemporaryDirectory() as tmp: fin, fout = Path(tmp) / "in.txt", Path(tmp) / "out.txt" fin.write_text("\n".join(str(int(v)) for v in x) + "\n") subprocess.run([str(exe), str(fin), str(fout)], check=True) return np.array([int(v) for v in fout.read_text().split()], dtype=np.int64) def test_coefficients_match_design() -> None: assert np.array_equal(coef_from_cpp(HERE / "fir_hls.cpp"), design_q15()) def test_c_simulation_self_checks(tb_exe: Path) -> None: run = subprocess.run([str(tb_exe)], capture_output=True, text=True) assert run.returncode == 0, run.stdout assert "PASS" in run.stdout def test_random_input_bit_exact(tb_exe: Path) -> None: rng = np.random.default_rng(7) x = rng.integers(-32768, 32768, size=8000) assert np.array_equal(run_kernel(tb_exe, x), fir_q15(x, design_q15())) def test_tones_bit_exact_and_close_to_float(tb_exe: Path) -> None: """Passband tone survives, stopband tone is attenuated, error vs float filter is small.""" rng = np.random.default_rng(8) n = np.arange(4800) fs = 48_000.0 x_f = 0.4 * np.sin(2 * np.pi * 1_000 * n / fs) + 0.4 * np.sin(2 * np.pi * 15_000 * n / fs) x_f += 0.01 * rng.standard_normal(n.size) x = np.round(x_f * (1 << FRAC)).astype(np.int64) y = run_kernel(tb_exe, x) h_q = design_q15() assert np.array_equal(y, fir_q15(x, h_q)) # Float reference with the same quantised coefficients: the only extra # error is the final rounding, at most half an LSB. y_float = np.convolve(x / 32768.0, h_q / 32768.0)[: x.size] assert np.max(np.abs(y / 32768.0 - y_float)) <= 0.5 / 32768 + 1e-12 # 15 kHz lies in the stopband: compare tone amplitudes after the transient. def amp(sig: np.ndarray, f: float) -> float: seg = sig[100:] ref = np.exp(-2j * np.pi * f * np.arange(100, sig.size) / fs) return 2 * abs(np.mean(seg * ref)) assert amp(y / 32768.0, 1_000) > 0.39 # input amplitude 0.4, passband gain about 1 assert amp(y / 32768.0, 15_000) < 0.002 # stopband: below 0.5 % of the input amplitude