"""cocotb tests for fir_transposed.sv, checked bit-exactly against fir_model.py. The pytest wrapper test_cocotb_fir.py builds the design and runs these tests. The coefficients under test come from the COEFS_INT environment variable (comma-separated integers), so the same tests run on several filters. """ from __future__ import annotations import os import cocotb import numpy as np from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, RisingEdge from fir_model import design_lowpass, fir_q15, quantise def coefficients() -> np.ndarray: text = os.environ.get("COEFS_INT", "") if text: return np.array([int(v) for v in text.split(",")], dtype=np.int64) return quantise(design_lowpass()) async def reset(dut) -> None: cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) dut.rst.value = 1 dut.in_valid.value = 0 dut.x.value = 0 await ClockCycles(dut.clk, 3) await FallingEdge(dut.clk) dut.rst.value = 0 async def run_samples(dut, samples: np.ndarray, gap_prob: float, rng: np.random.Generator) -> list[int]: """Drive samples (with random idle cycles) and collect every valid output.""" outputs: list[int] = [] async def monitor() -> None: while True: await RisingEdge(dut.clk) if dut.out_valid.value == 1: outputs.append(dut.y.value.to_signed()) mon = cocotb.start_soon(monitor()) for s in samples: while rng.random() < gap_prob: # idle cycle: in_valid low dut.in_valid.value = 0 await FallingEdge(dut.clk) dut.in_valid.value = 1 dut.x.value = int(s) await FallingEdge(dut.clk) dut.in_valid.value = 0 await ClockCycles(dut.clk, 8) mon.cancel() return outputs def check(dut, samples: np.ndarray, got: list[int]) -> None: expected = fir_q15(samples, coefficients()).tolist() assert len(got) == len(expected), f"{len(got)} outputs, expected {len(expected)}" bad = [i for i, (g, e) in enumerate(zip(got, expected)) if g != e] assert not bad, f"first mismatch at sample {bad[0]}: got {got[bad[0]]}, expected {expected[bad[0]]}" dut._log.info(f"{len(got)} outputs match the model bit for bit") @cocotb.test() async def impulse_response(dut) -> None: """A full-scale positive impulse returns the coefficients (rounded to Q1.15).""" await reset(dut) h = coefficients() samples = np.zeros(len(h) + 4, dtype=np.int64) samples[0] = 32767 got = await run_samples(dut, samples, 0.0, np.random.default_rng(1)) check(dut, samples, got) @cocotb.test() async def random_samples(dut) -> None: """Random full-range samples with random gaps in in_valid.""" await reset(dut) rng = np.random.default_rng(2026) samples = rng.integers(-32768, 32768, size=600) got = await run_samples(dut, samples, 0.3, rng) check(dut, samples, got) @cocotb.test() async def saturation(dut) -> None: """Worst-case input: samples follow the coefficient signs, so the sum exceeds full scale.""" await reset(dut) h = coefficients() pattern = np.where(h[::-1] >= 0, 32767, -32768) samples = np.concatenate([pattern, np.clip(-pattern, -32768, 32767), pattern]) got = await run_samples(dut, samples, 0.0, np.random.default_rng(3)) check(dut, samples, got) if np.abs(h).sum() > (1 << 15): assert 32767 in got and -32768 in got, "saturation was not exercised" @cocotb.test() async def sine_tones(dut) -> None: """A pass-band tone and a stop-band tone: the second is attenuated.""" await reset(dut) n = np.arange(400) tone = np.round(12000 * np.sin(2 * np.pi * 0.02 * n) + 12000 * np.sin(2 * np.pi * 0.4 * n)).astype(np.int64) got = await run_samples(dut, tone, 0.1, np.random.default_rng(4)) check(dut, tone, got)