蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线仿真 15 阶对称折叠并行 FIR 卷积一致性、7.5MHz 抑制与 16 拍瞬态

PYTHONWindows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。explore-fir.py
explore-fir.py160 行
"""Offline Verilog RTL verification lab for Chapter 30 (fir)."""
import json
import math

VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"

HALF_COE = [11, 31, 63, 104, 152, 198, 235, 255]
FULL_COE = HALF_COE + list(reversed(HALF_COE))


def generate_mixed_signal_12bit(num_samples=200, fs=50e6, fc=0.25e6, fn=7.5e6):
    """Replicate the chapter's 250kHz + 7.5MHz mixed cosine stimulus quantized to 12-bit unsigned."""
    raw = [
        math.cos(2 * math.pi * fc * n / fs) + math.cos(2 * math.pi * fn * n / fs)
        for n in range(num_samples)
    ]
    lo, hi = min(raw), max(raw)
    norm = [2.0 * (v - lo) / (hi - lo) - 1.0 for v in raw]
    return [int(math.floor(2047 * v + 2048)) for v in norm]


def parallel_fir_step_stream(samples):
    """Bit-accurate symmetric 16-tap parallel FIR (8 pre-adders + 8 multipliers + adder tree)."""
    xin_reg = [0] * 16
    yout = []
    for x in samples:
        xin_reg = [x] + xin_reg[:15]
        add_reg = [xin_reg[i] + xin_reg[15 - i] for i in range(8)]
        mout = [add_reg[i] * HALF_COE[i] for i in range(8)]
        sum1 = mout[0] + mout[1] + mout[2] + mout[3]
        sum2 = mout[4] + mout[5] + mout[6] + mout[7]
        yout.append(sum1 + sum2)
    return yout


def dft_mag_at_bin(seq, k):
    n = len(seq)
    re = sum(seq[i] * math.cos(2 * math.pi * k * i / n) for i in range(n))
    im = sum(-seq[i] * math.sin(2 * math.pi * k * i / n) for i in range(n))
    return math.hypot(re, im)


def case_symmetric_folding_equivalence():
    """Verify 8-multiplier symmetric pre-add FIR matches 16-tap direct convolution bit-for-bit."""
    samples = generate_mixed_signal_12bit(64)
    folded = parallel_fir_step_stream(samples)
    direct = []
    for n in range(len(samples)):
        acc = 0
        for k in range(16):
            if n - k >= 0:
                acc += samples[n - k] * FULL_COE[k]
        direct.append(acc)
    expected = {
        "bit_exact_match": True,
        "dc_gain_sum": 2098,
        "max_possible_output": 4095 * 2098,
        "fits_29bit_unsigned": True,
    }
    actual = {
        "bit_exact_match": folded == direct,
        "dc_gain_sum": sum(FULL_COE),
        "max_possible_output": 4095 * sum(FULL_COE),
        "fits_29bit_unsigned": (4095 * sum(FULL_COE)) < (1 << 29),
    }
    return {
        "name": "symmetric_folding_equivalence",
        "summary": "验证对称折叠 8 乘法器并行 FIR 与 16 抽头直接卷积逐拍完全一致,且 29-bit 输出无溢出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lowpass_7p5mhz_rejection():
    """Verify 7.5MHz (bin 30) attenuation relative to 250kHz (bin 1) in steady-state 200-sample period."""
    one_period = generate_mixed_signal_12bit(200)
    # Feed 2 periods so the second period [200:400] is completely past the 16-sample startup transient
    yout = parallel_fir_step_stream(one_period * 2)
    steady = yout[200:400]
    in_250k = dft_mag_at_bin(one_period, 1)
    in_7p5m = dft_mag_at_bin(one_period, 30)
    out_250k = dft_mag_at_bin(steady, 1)
    out_7p5m = dft_mag_at_bin(steady, 30)
    # Rejection ratio in dB of 7.5MHz vs 250kHz after filtering
    suppression_db = 20.0 * math.log10((out_250k / in_250k) / (out_7p5m / in_7p5m))
    expected = {
        "input_ratio_near_1": True,
        "high_freq_suppression_gt_35db": True,
        "output_250k_preserved": True,
    }
    actual = {
        "input_ratio_near_1": abs(in_250k / in_7p5m - 1.0) < 0.05,
        "high_freq_suppression_gt_35db": suppression_db > 35.0,
        "output_250k_preserved": (out_250k / in_250k) > 2000.0,
    }
    return {
        "name": "lowpass_7p5mhz_rejection",
        "summary": "验证 50MHz 采样下 15 阶并行 FIR 完整保留 250kHz 信号并对 7.5MHz 高频实现 >35dB 抑制",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_startup_transient_16_cycles():
    """Verify the first 15 outputs are partial-window startup transient and steady response begins at tap 16."""
    const_in = [100] * 24
    yout = parallel_fir_step_stream(const_in)
    steady_val = 100 * sum(FULL_COE)
    first_steady_idx = next(i for i, v in enumerate(yout) if v == steady_val)
    expected = {"first_steady_index_0based": 15, "transient_samples": 15, "steady_dc_output": 209800}
    actual = {
        "first_steady_index_0based": first_steady_idx,
        "transient_samples": first_steady_idx,
        "steady_dc_output": yout[-1],
    }
    return {
        "name": "startup_transient_16_cycles",
        "summary": "验证 16 组移位寄存器填满前 15 拍为启动瞬态,自第 16 拍(索引 15)起进入稳态输出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_linear_phase_group_delay():
    """Verify even-symmetric 16-tap FIR has exact constant group delay (N-1)/2 = 7.5 samples."""
    is_symmetric = FULL_COE == list(reversed(FULL_COE))
    order = len(FULL_COE) - 1
    group_delay = order / 2.0
    expected = {"order": 15, "taps": 16, "symmetric": True, "group_delay_samples": 7.5}
    actual = {
        "order": order,
        "taps": len(FULL_COE),
        "symmetric": is_symmetric,
        "group_delay_samples": group_delay,
    }
    return {
        "name": "linear_phase_group_delay",
        "summary": "校验 15 阶偶对称 FIR 系数的线性相位条件及恒定群延迟 7.5 采样周期",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_symmetric_folding_equivalence(),
        case_lowpass_7p5mhz_rejection(),
        case_startup_transient_16_cycles(),
        case_linear_phase_group_delay(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。

入口文件:projects/verilog-fir-lab/explore-fir.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-fir.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Verilog

课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a2580.zip

下载课程关联工程包:Verilog

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2595.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习