Files
chenproject/fiber_delay_sim/tests/test_m2_m4.py
2026-10-12 16:25:51 +08:00

99 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""M2/M3/M4 验收测试(docs/实现方案.md §11–§12)。"""
import numpy as np
import pytest
from fiber_delay_sim import pipeline
from fiber_delay_sim.core import acquisition, calibration, fitting, signal, statistics
# ---------- M2:四通道误差注入与校准 ----------
def test_multi_channel_phase_grid():
"""四通道理想延时:等效时间网格应为 0/2.5/5/7.5 ns(+10ns 周期重复)。"""
t_cont = np.arange(0.0, 400.0, 0.01)
y_cont = signal.generate(t_cont, signal.PRESETS["single"])
rng = np.random.default_rng(1)
acq = acquisition.run_multi_channel(t_cont, y_cont, {
"delays": [0.0, 47.5, 95.0, 142.5],
"dt_ns": 10.0, "window_ns": 400.0, "snr_db": None, "bits": None,
}, rng)
assert acq["n_channels"] == 4
assert acq["n_samples"] == 40
# 等效时间 = t_adc − delay(含负值,应过滤)
cal = calibration.calibrate_channels(acq["channels"], 10.0, method="nominal")
assert cal["n_points"] > 0
phases = np.unique(np.round(cal["t_rebuilt"] % 10.0, 6))
# 应覆盖 0/2.5/5/7.5 四个相位(±0.1 容差,考虑尾部裁剪)
expected = {0.0, 2.5, 5.0, 7.5}
found = {float(p) for p in phases if p < 10}
assert expected <= found or len(expected & found) >= 4
def test_m2_calibration_improves_fit():
"""M2 验收:注入误差后,完整校准比不校准的(1)重建曲线更连续、(2)τ̂ 有界。"""
rec = pipeline.run_m2({"snr_db": 60.0, "bits": 14}, seed=42)
j_raw = rec["raw"]["continuity"]["mean_jump"]
j_cal = rec["calibrated"]["continuity"]["mean_jump"]
assert j_cal < j_raw # 校准消除通道断层(连续度改善)
err = abs(rec["calibrated"]["tau_hat"] - rec["tau_true"]) / rec["tau_true"]
assert err < 0.05
assert rec["calibrated"]["tau_hat"] is not None
def test_m2_zero_error_ideal():
"""零误差 + 理想条件:不校准(raw)也应精确恢复设定寿命(真值基线天然为 0)。"""
rec = pipeline.run_m2({"gain_errors": [0.0] * 4, "delay_errors": [0.0] * 4,
"baselines": [0.0] * 4, "calib_residual_ns": 0.0,
"snr_db": None, "bits": None}, seed=3)
d_raw = abs(rec["raw"]["tau_hat"] - rec["tau_true"]) / rec["tau_true"]
assert d_raw < 1e-6
def test_m3_algorithms_on_noisy_data():
"""三档 SNR 下:NLS 有界(<5%);默认"尾段估基线"的对数线性因基线误差显著劣于 NLS。"""
t = np.arange(0.0, 400.0, 10.0)
for snr in (30.0, 50.0, 70.0):
errs_nls, errs_ll = [], []
for s in range(8):
rng = np.random.default_rng(s)
y = np.exp(-t / 52.8)
sigma = np.max(y) * 10 ** (-snr / 20)
yn = y + rng.normal(0, sigma, len(t))
r_nls = fitting.fit_single_exp_nls(t, yn)
errs_nls.append(abs(r_nls["tau"] - 52.8) / 52.8)
r_ll = fitting.fit_log_linear(t, yn) # 默认尾段估基线(学生常规操作)
if r_ll["tau"]:
errs_ll.append(abs(r_ll["tau"] - 52.8) / 52.8)
assert np.mean(errs_nls) < 0.05 # NLS 稳健
assert len(errs_ll) > 0
assert np.mean(errs_ll) > np.mean(errs_nls) # 估基线 → 对数线性系统偏差
# ---------- M4:单通道 vs 四相位蒙特卡洛 ----------
def test_m4_single_vs_fiber_relstd():
"""M4 验收:四相位等效采样 τ₂ 相对标准差应显著低于单通道(复现原项目量级)。"""
cmp = pipeline.run_m4_compare(repeats=40, seed=0, snr_db=50.0)
s, f = cmp["single"]["rel_std"], cmp["fiber"]["rel_std"]
assert s is not None and f is not None
assert f < s * 0.5 # 精度提升至少一半以上
assert f < 0.02 # 四相位 τ₂ 相对标准差应 < 2%
print(f"[M4] 单通道 rel_std={s:.3%} vs 四相位={f:.3%}")
def test_m4_failure_rate_drops():
"""失败率(|Δτ/τ|>5%)应在四相位下显著降低。"""
cmp = pipeline.run_m4_compare(repeats=40, seed=1, snr_db=40.0)
fr_s = cmp["single"]["failure_rate"]
fr_f = cmp["fiber"]["failure_rate"]
assert fr_f <= fr_s
def test_statistics_confidence_interval():
"""置信区间:已知真值应落在 95% CI 附近(教学正态近似)。"""
rng = np.random.default_rng(0)
vals = rng.normal(52.8, 0.5, 200)
ci = statistics.confidence_interval(vals)
assert abs(ci["mean"] - 52.8) < 0.15
assert ci["ci_lo"] < 52.8 < ci["ci_hi"]