"""cocotb test for sobel_pipeline.sv: stream synthetic images in raster order with random gaps in in_valid and compare every output pixel with sobel_model.py.""" from __future__ import annotations import random import cocotb import numpy as np from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, RisingEdge from sobel_model import stream_expected, synthetic_image W, H, THRESH = 32, 20, 400 # must match test_cocotb_sobel.py @cocotb.test() async def two_frames_with_gaps(dut) -> None: cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) rng = random.Random(2020) dut.rst.value = 1 dut.in_valid.value = 0 dut.in_sof.value = 0 await ClockCycles(dut.clk, 3) await FallingEdge(dut.clk) dut.rst.value = 0 images = [synthetic_image(W, H, seed=s) for s in (3, 4)] pixels = [(f, y, x) for f in range(len(images)) for y in range(H) for x in range(W)] got_mag: list[int] = [] got_edge: list[int] = [] sof_seen: list[int] = [] async def collect() -> None: while True: await RisingEdge(dut.clk) await FallingEdge(dut.clk) if int(dut.out_valid.value): if int(dut.out_sof.value): sof_seen.append(len(got_mag)) got_mag.append(int(dut.mag.value)) got_edge.append(int(dut.edge_out.value)) cocotb.start_soon(collect()) i = 0 while i < len(pixels): if rng.random() < 0.75: # valid with probability 0.75 f, y, x = pixels[i] r, g, b = (int(v) for v in images[f][y, x]) dut.r.value, dut.g.value, dut.b.value = r, g, b dut.in_valid.value = 1 dut.in_sof.value = int(x == 0 and y == 0) i += 1 else: dut.in_valid.value = 0 dut.in_sof.value = 0 dut.r.value = rng.randrange(256) # garbage on idle cycles await FallingEdge(dut.clk) dut.in_valid.value = 0 dut.in_sof.value = 0 await ClockCycles(dut.clk, 10) assert len(got_mag) == len(pixels), f"{len(got_mag)} outputs for {len(pixels)} inputs" assert sof_seen == [0, W * H], f"start-of-frame flags at {sof_seen}" for f, img in enumerate(images): mag_ref, edge_ref = stream_expected(img, THRESH) n0 = f * W * H mag = np.array(got_mag[n0:n0 + W * H], dtype=np.uint8).reshape(H, W) edge = np.array(got_edge[n0:n0 + W * H], dtype=np.uint8).reshape(H, W) bad = np.argwhere(mag != mag_ref) assert bad.size == 0, f"frame {f}: mag differs at (y, x) = {tuple(bad[0])}" assert np.array_equal(edge, edge_ref), f"frame {f}: edge map differs" dut._log.info(f"frame {f}: {W * H} pixels match, {int(edge.sum())} edge pixels")