如何注入噪声模型并验证纠错码?
解读
在国内 Python 测试面试里,这道题表面问“噪声+纠错”,实则考察三件事:
- 能否把“非功能性”算法验证拆成可自动化、可回归的测试用例;
- 是否熟悉 Pytest 的 fixture、参数化、插件体系,能把“随机性”做成“可重复、可断言”;
- 是否理解“测试即规格”——用代码把需求(纠错能力)描述清楚,而不是口头说“我觉得能纠 1 bit”。
因此,回答必须给出一条从“噪声模型注入”到“断言纠错成功”的完整 pytest 流水线,并体现大陆开发者的工程习惯:依赖隔离、CI 友好、覆盖率可上报。
知识点
- 信道噪声模型:BSC(二进制对称信道)、AWGN(加性高斯白噪声)的 Python 实现;
- 线性分组码/汉明码、RS 码或 LDPC 的编解码接口(可用 scipy、ldpc、reedsolo 等库,但面试时只需接口,不纠结实现);
- Pytest fixture 的 scope 与依赖注入:用 factory fixture 动态生成“加噪”数据;
- pytest.mark.parametrize 与自定义 mark(如 smoke、error_rate)实现多组误码率覆盖;
- pytest-randomly 或自写 seed fixture,保证随机噪声可复现;
- pytest-parallel/pytest-xdist 在 CI 并行跑 1e4 条随机帧而不拖慢流水线;
- coverage.py + pytest-cov 统计编解码分支覆盖,满足国内甲方≥90% 行覆盖要求;
- 断言策略:用 numpy.testing.assert_array_equal 比较纠错后码字与原始码字,同时用 allclose 容忍浮点 AWGN 量化误差;
- 性能基线:用 pytest-benchmark 记录解码耗时,防止后续 MR 引入回归;
- 测试报告:pytest-html 生成中文报告,供测试经理归档。
答案
下面给出一个可直接落地到 GitLab CI(国内常见)的 pytest 方案,实现“注入 BSC 噪声并验证汉明码(7,4) 能纠 1 bit”。
项目结构 hamming/ ├── hamming.py # 纯 Python 编解码实现 ├── test_noise.py # 测试用例 ├── conftest.py # fixture 与 mark 配置 └── requirements.txt # 依赖列表
hamming.py(极简实现,面试现场可白板上写)
import numpy as np
def encode_74(bits: np.ndarray) -> np.ndarray:
"""bits: length-4 array, return length-7 codeword"""
G = np.array([
[1,0,0,0,1,1,0],
[0,1,0,0,1,0,1],
[0,0,1,0,0,1,1],
[0,0,0,1,1,1,1]
], dtype=np.uint8)
return (bits @ G) % 2
def decode_74(codeword: np.ndarray) -> np.ndarray:
"""return length-4 message"""
H = np.array([
[1,1,0,1,1,0,0],
[1,0,1,1,0,1,0],
[0,1,1,1,0,0,1]
], dtype=np.uint8)
syndrome = (H @ codeword) % 2
error_pos = int(''.join(map(str, syndrome)), 2)
if error_pos:
codeword = codeword.copy()
codeword[error_pos-1] ^= 1
return codeword[:4]
conftest.py
import pytest
import numpy as np
def pytest_configure(config):
config.addinivalue_line("markers", "error_rate(p): 指定误码概率")
@pytest.fixture(scope='session')
def rng():
"""全局复现随机源,国内 CI 必须可复现"""
return np.random.default_rng(42)
@pytest.fixture
def bsc_noise(rng):
"""返回一个工厂函数,调用时注入噪声"""
def _add_noise(codeword: np.ndarray, p: float):
flip = rng.random(size=codeword.shape) < p
return (codeword + flip) % 2
return _add_noise
test_noise.py
import pytest
import numpy as np
from hamming import encode_74, decode_74
class TestHammingNoise:
@pytest.mark.parametrize("msg_int", range(16)) # 穷举 4 bit 消息
@pytest.mark.error_rate(0.0)
def test_0_noise(self, msg_int):
"""0 噪声基线"""
msg = np.array(list(map(int, f"{msg_int:04b}")), dtype=np.uint8)
cw = encode_74(msg)
rcv = decode_74(cw)
np.testing.assert_array_equal(rcv, msg)
@pytest.mark.parametrize("trial", range(100)) # 100 次蒙特卡洛
@pytest.mark.error_rate(0.1)
def test_1_bit_error(self, trial, bsc_noise):
"""BSC p=0.1,期望汉明距能纠 1 bit"""
rng = np.random.default_rng(trial) # 每条用例独立种子
msg = rng.integers(0, 2, size=4, dtype=np.uint8)
cw = encode_74(msg)
noisy = bsc_noise(cw, 0.1)
rcv = decode_74(noisy)
np.testing.assert_array_equal(rcv, msg)
@pytest.mark.error_rate(0.25)
def test_2_bit_error_detect_only(self, bsc_noise):
"""2 bit 错已超出纠错能力,应断言解码结果≠原消息(至少不崩溃)"""
msg = np.array([1,0,1,0], dtype=np.uint8)
cw = encode_74(msg)
noisy = bsc_noise(cw, 0.25)
# 人工注入恰好 2 bit
noisy[0] ^= 1
noisy[1] ^= 1
rcv = decode_74(noisy)
# 只要解码不抛异常即可,不保证正确
assert rcv.shape == (4,)
运行与报告
pip install -r requirements.txt
pytest -q -n auto --cov=hamming --cov-report=term-missing --html=report.html
国内 GitLab Runner 上再加:
script:
- pytest -n 8 --cov=hamming --cov-report=xml --junitxml=junit.xml
- coverage xml -o coverage.xml
artifacts:
reports:
junit: junit.xml
coverage_report:
coverage_format: cobertura
path: coverage.xml
即可在 MR 页面直接看到行覆盖 100%,测试经理无需手动跑脚本。
拓展思考
- 若噪声模型换成 AWGN,需把“硬判决”改成“软判决”,测试断言从“比特完全一致”变为“误帧率<1e-3”。可用 pytest-approx 做浮点断言,并用 factory fixture 把 SNR 作为参数传入,实现“连续 10 个 SNR 点自动回归”。
- 对于 LDPC、Polar 等 5G 场景,解码采用迭代置信传播,可能出现“不收敛”异常。此时需用 pytest.raises 捕获自定义 DecodeFailure,并统计在不同 Eb/N0 下的收敛率,作为验收 KPI。
- 国内车规/医疗行业要求“故障注入测试”必须可追溯。可借助 pytest-harvest 把每条随机帧的 seed、误码位置、解码结果持久化到 csv,供审核人员反向复现。
- 性能方面,若解码耗时 >10 ms,可能被产线判为“超时”。可用 pytest-benchmark 的
--benchmark-json输出到 GitLab CI,设置阈值 gate:若均值耗时上涨 15% 则 MR 无法合并。 - 最后,测试代码本身也需被测试。可写“元测试”:人为构造不可纠图案,确保 decode_74 不会误纠,并断言解码后 CRC 失败,从而验证“负向场景”也被覆盖——这一点是国内高级测试工程师的加分项。