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

离线仿真 8 点基-2 DIT Q13 定点 FFT、旋转因子补码编码与 DFT 误差对比

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

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

# Q13 fixed-point twiddle factors (scaled by 8192 = 0x2000), matching chapter Verilog fft8
TWIDDLE_Q13 = [
    (0x2000, 0x0000),              # W8^0 = 1
    (0x16A0, -0x16A1),             # W8^1: 16'h16a0 (+5792), 16'he95f (-5793)
    (0x0000, -0x2000),             # W8^2: 0, 16'he000 (-8192)
    (-0x16A1, -0x16A1),            # W8^3: 16'he95f (-5793), 16'he95f (-5793)
]


def bit_reverse_indices(n):
    bits = int(math.log2(n))
    return [int(f"{i:0{bits}b}"[::-1], 2) for i in range(n)]


def butterfly_q13(xp_r, xp_i, xq_r, xq_i, wr, wi):
    """Bit-accurate model of Verilog butterfly module (shift left 13 on xp, discard low 13 bits)."""
    xq_wr = xq_r * wr - xq_i * wi
    xq_wi = xq_r * wi + xq_i * wr
    xp_r_s = xp_r << 13
    xp_i_s = xp_i << 13
    yp_r = (xp_r_s + xq_wr) >> 13
    yp_i = (xp_i_s + xq_wi) >> 13
    yq_r = (xp_r_s - xq_wr) >> 13
    yq_i = (xp_i_s - xq_wi) >> 13
    return (yp_r, yp_i), (yq_r, yq_i)


def fft8_fixed_q13(vec):
    """3-stage radix-2 DIT 8-point fixed-point FFT matching chapter fft8.v."""
    order = bit_reverse_indices(8)
    stage = [vec[i] for i in order]
    # Stage m=0: distance=1, 4 groups of 1 butterfly, W8^0
    # Stage m=1: distance=2, 2 groups of 2 butterflies, W8^0, W8^2 (note: chapter code uses factor[0], factor[1]!)
    # Let's implement standard radix-2 DIT twiddle stride (k_in_group * (4 >> m))
    for m in range(3):
        half = 1 << m
        step = half << 1
        tw_stride = 4 >> m
        nxt = [None] * 8
        for grp_start in range(0, 8, step):
            for j in range(half):
                p = grp_start + j
                q = p + half
                wr, wi = TWIDDLE_Q13[j * tw_stride]
                nxt[p], nxt[q] = butterfly_q13(stage[p][0], stage[p][1], stage[q][0], stage[q][1], wr, wi)
        stage = nxt
    return stage


def dft_ref(vec):
    n = len(vec)
    out = []
    for k in range(n):
        acc = 0j
        for i, (r, im) in enumerate(vec):
            acc += complex(r, im) * cmath.exp(-2j * math.pi * k * i / n)
        out.append(acc)
    return out


def case_bit_reversal_and_complexity():
    """Verify 8-point bit-reversal order and radix-2 butterfly multiplication/addition counts."""
    rev = bit_reverse_indices(8)
    n = 8
    stages = int(math.log2(n))
    butterflies_per_stage = n // 2
    total_mults = (n // 2) * stages
    total_adds = n * stages
    expected = {
        "bit_reversed_order": [0, 4, 2, 6, 1, 5, 3, 7],
        "stages_M": 3,
        "groups_per_stage": [4, 2, 1],
        "total_complex_mults": 12,
        "total_complex_adds": 24,
    }
    actual = {
        "bit_reversed_order": rev,
        "stages_M": stages,
        "groups_per_stage": [n // (2 << m) for m in range(stages)],
        "total_complex_mults": total_mults,
        "total_complex_adds": total_adds,
    }
    return {
        "name": "bit_reversal_and_complexity",
        "summary": "校验 8 点基-2 FFT 的码位倒置序列、3 级组分布(4/2/1)及 12 复乘/24 复加复杂度",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_twiddle_q13_quantization():
    """Verify Q13 (x8192) two's complement hex encodings of W8^0..W8^3 match chapter fft8.v."""
    hex_table = []
    for r in range(4):
        w = cmath.exp(-1j * math.pi * r / 4.0)
        re_i = math.floor(w.real * 8192)
        im_i = math.floor(w.imag * 8192)
        re_u16 = re_i & 0xFFFF
        im_u16 = im_i & 0xFFFF
        hex_table.append((f"{re_u16:04x}", f"{im_u16:04x}"))
    expected = [
        ("2000", "0000"),
        ("16a0", "e95f"),
        ("0000", "e000"),
        ("e95f", "e95f"),
    ]
    return {
        "name": "twiddle_q13_quantization",
        "summary": "校验 8 点 FFT 旋转因子 W8^0~W8^3 放大 8192 倍后的 16-bit 补码十六进制编码",
        "expected": expected,
        "actual": hex_table,
        "passed": hex_table == expected,
    }


def case_fft8_real_vector_exact_match():
    """Verify chapter's first test vector [10,20,30,40,10,20,30,40] matches floating DFT exactly."""
    vec = [(v, 0) for v in (10, 20, 30, 40, 10, 20, 30, 40)]
    fixed = fft8_fixed_q13(vec)
    ref = [(round(c.real), round(c.imag)) for c in dft_ref(vec)]
    expected = {
        "exact_match_with_dft": True,
        "dc_bin0": [200, 0],
        "bin2": [-40, 40],
        "bin4": [-40, 0],
        "bin6": [-40, -40],
    }
    actual = {
        "exact_match_with_dft": fixed == ref,
        "dc_bin0": list(fixed[0]),
        "bin2": list(fixed[2]),
        "bin4": list(fixed[4]),
        "bin6": list(fixed[6]),
    }
    return {
        "name": "fft8_real_vector_exact_match",
        "summary": "验证实部输入 [10,20,30,40,10,20,30,40] 的 Q13 定点 8 点 FFT 与浮点 DFT 精确一致",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_fft8_complex_quantization_error():
    """Compare Q13 fixed-point FFT vs double-precision DFT on chapter's complex test vector 2."""
    x1 = [10, 20, 30, 40, 10, 20, 30, 40]
    step = [(1, 2), (1, 5), (31, 3), (1, 6), (23, 4), (1, 8), (6, 11), (1, 7)]
    vec2 = [(x1[i] + step[i][0], step[i][1]) for i in range(8)]
    fixed = fft8_fixed_q13(vec2)
    ref = dft_ref(vec2)
    max_abs_err = max(abs(complex(r, im) - c) for (r, im), c in zip(fixed, ref))
    # Verify Parseval energy conservation within small fixed-point truncation bound
    time_energy = sum(r * r + im * im for r, im in vec2)
    freq_energy_ref = sum(abs(c) ** 2 for c in ref) / 8.0
    expected = {
        "max_fixed_truncation_err_lt_2p5": True,
        "parseval_ref_exact": True,
    }
    actual = {
        "max_fixed_truncation_err_lt_2p5": max_abs_err < 2.5,
        "parseval_ref_exact": abs(time_energy - freq_energy_ref) < 1e-6,
    }
    return {
        "name": "fft8_complex_quantization_error",
        "summary": "对比复数输入向量下 Q13 定点截位 FFT 与高精度浮点 DFT 的最大量化误差与帕塞瓦尔能量守恒",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_bit_reversal_and_complexity(),
        case_twiddle_q13_quantization(),
        case_fft8_real_vector_exact_match(),
        case_fft8_complex_quantization_error(),
    ]
    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-fft-lab/explore-fft.py

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

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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