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

离线仿真 DDC 频谱搬移、诺布尔恒等式与 3 级 D=5 CIC 21-bit/34-bit 回绕不变性

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

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


def generate_mixed_signal_12bit(num_samples=200, fs=50e6, fc=0.25e6, fn=7.5e6):
    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 sim_cic_3stage(samples, d=5, nmax=21):
    """Bit-accurate 3-stage CIC decimator (N=3, M=1, D=5) with modular NMAX-bit arithmetic."""
    mask = (1 << nmax) - 1
    i0 = i1 = i2 = 0
    cnt = 0
    d1 = d1_d = d2 = d2_d = d3 = d3_d = 0
    decimated = []
    comb_out = []
    for x in samples:
        i0 = (i0 + x) & mask
        i1 = (i1 + i0) & mask
        i2 = (i2 + i1) & mask
        if cnt == d - 1:
            cnt = 0
            decimated.append(i2)
            # 3-stage comb differential (modular subtraction cancels wrap-around!)
            d1_d, d1 = d1, i2
            s1 = (d1 - d1_d) & mask
            d2_d, d2 = d2, s1
            s2 = (d2 - d2_d) & mask
            d3_d, d3 = d3, s2
            s3 = (d3 - d3_d) & mask
            comb_out.append(s3)
        else:
            cnt += 1
    return decimated, comb_out


def case_bandpass_sampling_and_ddc_shift():
    """Verify bandpass sampling theorem and 60MHz+/-4MHz DDC down-conversion at Fs=80MHz, NCO=20MHz."""
    f_center, bw = 60.0, 8.0
    f_low, f_high = f_center - bw / 2, f_center + bw / 2  # 56..64 MHz
    m = 1
    fs_min = 2 * f_high / (m + 1)  # 64 MHz
    fs_max = 2 * f_low / m         # 112 MHz
    fs = 80.0
    nco = 20.0
    # Aliasing of [56, 64] at Fs=80 -> [-24, -16] MHz; mix with +20MHz NCO -> [-4, +4] MHz baseband
    aliased_band = [f_low - fs, f_high - fs]
    baseband = [aliased_band[0] + nco, aliased_band[1] + nco]
    expected = {
        "fs_range_m1_mhz": [64.0, 112.0],
        "fs_80_valid": True,
        "aliased_band_mhz": [-24.0, -16.0],
        "zero_if_baseband_mhz": [-4.0, 4.0],
    }
    actual = {
        "fs_range_m1_mhz": [fs_min, fs_max],
        "fs_80_valid": fs_min <= fs <= fs_max,
        "aliased_band_mhz": aliased_band,
        "zero_if_baseband_mhz": baseband,
    }
    return {
        "name": "bandpass_sampling_and_ddc_shift",
        "summary": "验证带通采样定理(m=1 时 Fs 在 64~112MHz)及 80MHz 采样 + 20MHz NCO 零中频搬移",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cic_bit_growth_and_modular_invariance():
    """Verify Hogenauer bit-growth formula B_max = ceil(N*log2(D*M) + B_in) and 21-bit vs 34-bit invariance."""
    b_in, n_stages, d, m = 12, 3, 5, 1
    b_exact = math.ceil(n_stages * math.log2(d * m) + b_in)  # ceil(3*2.3219 + 12) = 19 -> +1/+2 margin = 20/21
    dc_gain = (d * m) ** n_stages  # 5^3 = 125
    # Max unsigned output for 12-bit input 4095: 4095 * 125 = 511,875 < 2^19 (524,288) -> 21-bit has ample margin
    samples = generate_mixed_signal_12bit(200) * 3
    _, out_21 = sim_cic_3stage(samples, d=5, nmax=21)
    _, out_34 = sim_cic_3stage(samples, d=5, nmax=34)
    # After initial 3 comb stages settle, 21-bit wrapping integrator gives IDENTICAL comb output to 34-bit!
    identical_after_settle = out_21[5:] == out_34[5:]
    expected = {
        "hogenauer_min_bits": 19,
        "dc_gain": 125,
        "max_output_fits_21bit": True,
        "out_21bit_equals_out_34bit": True,
    }
    actual = {
        "hogenauer_min_bits": b_exact,
        "dc_gain": dc_gain,
        "max_output_fits_21bit": (4095 * dc_gain) < (1 << 21),
        "out_21bit_equals_out_34bit": identical_after_settle,
    }
    return {
        "name": "cic_bit_growth_and_modular_invariance",
        "summary": "验证 3 级 D=5 CIC 位宽增长与模算术不变性:21-bit 积分器锯齿回绕与 34-bit 输出完全一致",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cic_decimation_and_highfreq_rejection():
    """Verify D=5 decimation lowers Fs 50MHz->10MHz (cutoff 5MHz) and strongly attenuates 7.5MHz."""
    one_period = generate_mixed_signal_12bit(200)  # 1 cycle of 250kHz at 50MHz -> 40 samples/cycle at 10MHz
    _, out = sim_cic_3stage(one_period * 4, d=5, nmax=21)
    steady = out[80:120]  # 40 samples = 1 full cycle of 250kHz at 10MHz Fs_out
    # At 10MHz, 250kHz is bin 1; 7.5MHz aliases to 2.5MHz which is bin 10
    def mag(seq, k):
        n = len(seq)
        return math.hypot(
            sum(seq[i] * math.cos(2 * math.pi * k * i / n) for i in range(n)),
            sum(-seq[i] * math.sin(2 * math.pi * k * i / n) for i in range(n)),
        )

    m_250k = mag(steady, 1)
    m_alias_7p5m = mag(steady, 10)
    ratio_db = 20.0 * math.log10(m_250k / max(m_alias_7p5m, 1e-9))
    expected = {
        "output_rate_mhz": 10.0,
        "samples_per_250k_cycle": 40,
        "rejection_gt_30db": True,
    }
    actual = {
        "output_rate_mhz": 50.0 / 5,
        "samples_per_250k_cycle": len(steady),
        "rejection_gt_30db": ratio_db > 30.0,
    }
    return {
        "name": "cic_decimation_and_highfreq_rejection",
        "summary": "验证 D=5 抽取将采样率由 50MHz 降至 10MHz,并验证 250kHz 保留与 7.5MHz 混叠分量衰减 >30dB",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cic_noble_identity_equivalence():
    """Verify Noble Identity: H(z)=((1-z^-5)/(1-z^-1))^3 equals 3-stage integrator -> D=5 -> 3-stage comb."""
    # Direct FIR impulse response of ((1+z^-1+z^-2+z^-3+z^-4)^3) has length 3*(5-1)+1 = 13
    h1 = [1, 1, 1, 1, 1]
    def conv(a, b):
        res = [0] * (len(a) + len(b) - 1)
        for i, va in enumerate(a):
            for j, vb in enumerate(b):
                res[i + j] += va * vb
        return res
    h3 = conv(conv(h1, h1), h1)
    # Feed impulse sequence [0,0,0,0, 1, 0, ...] aligned to decimation phase
    test_sig = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] * 4
    _, cic_y = sim_cic_3stage(test_sig, d=5, nmax=34)
    fir_y = []
    for n in range(len(test_sig)):
        if n % 5 == 4:
            val = sum(test_sig[n - k] * h3[k] for k in range(len(h3)) if n - k >= 0)
            fir_y.append(val)
    expected = {
        "impulse_len": 13,
        "impulse_sum": 125,
        "noble_identity_exact_match": True,
    }
    actual = {
        "impulse_len": len(h3),
        "impulse_sum": sum(h3),
        "noble_identity_exact_match": cic_y == fir_y,
    }
    return {
        "name": "cic_noble_identity_equivalence",
        "summary": "验证诺布尔恒等式:多级积分->抽取->梳状结构与等效 13 抽头盒式卷积再抽取逐点相等",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_bandpass_sampling_and_ddc_shift(),
        case_cic_bit_growth_and_modular_invariance(),
        case_cic_decimation_and_highfreq_rejection(),
        case_cic_noble_identity_equivalence(),
    ]
    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-cic-lab/explore-cic.py

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

下载课程关联工程包:Verilog

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

下载课程关联工程包:Verilog

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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