Files
chenproject/fiber_delay_sim/experiments/exp06_m4_scan.py
douboer 42cb251061 update at 2026-10-12 16:53:40
网站v8修复(时序竞态+M3表格) + exp06 SNR×窗口扫描 + README里程碑更新
2026-10-12 16:53:41 +08:00

107 lines
5.2 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.

"""M4 补充实验:SNR × 记录窗口 参数扫描 —— 复现原项目"单通道发散 vs 四相位收敛"量级区。
运行:python -m fiber_delay_sim.experiments.exp06_m4_scan [--repeats 40]
产出:提升比热图 + 特征曲线 + 失败率表,落盘记录包 exp06_m4_snr_window_scan。
"""
import argparse
import numpy as np
from .. import pipeline
from ..export import record
from ._plot import setup_style
def run(repeats=40, runs_dir="runs"):
plt = setup_style()
snrs = [25, 30, 35, 40, 45, 50, 60, 80]
wins = [100, 150, 200, 300, 400]
def scan_one(snr, win):
p = dict(pipeline.M4_DEFAULTS)
p["snr_db"] = float(snr)
p["window_ns"] = float(win)
st_s = pipeline.statistics.monte_carlo(
lambda sd, p=p: pipeline._gen_single(sd, p), repeats=repeats, seed=0, tau_true=52.80)
st_f = pipeline.statistics.monte_carlo(
lambda sd, p=p: pipeline._gen_fiber(sd, p), repeats=repeats, seed=0, tau_true=52.80)
rs = st_s["rel_std"] * 100 if st_s["rel_std"] else float("nan")
rf = st_f["rel_std"] * 100 if st_f["rel_std"] else float("nan")
ratio = rs / rf if rf and rf > 0 else float("inf")
fr_s = (st_s.get("failure_rate") or 0) * 100
fr_f = (st_f.get("failure_rate") or 0) * 100
print(f" SNR {snr:>2} dB, win {win:>3} ns: single={rs:7.2f}% fiber={rf:6.2f}% ratio={ratio:6.1f}x "
f"fail率 {fr_s:5.1f}%/{fr_f:5.1f}%", flush=True)
return {"snr_db": snr, "window_ns": win,
"single_rel_std": rs, "fiber_rel_std": rf, "ratio": ratio,
"single_fail": st_s["n_failed"], "fiber_fail": st_f["n_failed"],
"single_failure_rate": fr_s, "fiber_failure_rate": fr_f,
"single_bias": (st_s.get("bias") or 0) * 100,
"fiber_bias": (st_f.get("bias") or 0) * 100}
rows = [scan_one(snr, win) for snr in snrs for win in wins]
# ---------- 图 1:提升比热图(SNR × 窗口) ----------
import matplotlib.colors as mcolors
Z = np.array([[r["ratio"] for r in rows if r["snr_db"] == s] for s in snrs]) # 行=SNR
Z = np.nan_to_num(Z, nan=0.0, posinf=0.0)
fig, ax = plt.subplots(figsize=(7.6, 4.8))
vmax = max(10.0, Z.max())
norm = mcolors.LogNorm(vmin=max(Z.max() / 100, 1.0), vmax=vmax)
# pcolormesh:x/y 单元格宽度按真实刻度间距,避免不等步长误导
x_edges = [w - 25 for w in wins] + [wins[-1] + 25]
y_edges = [s - 2.5 for s in snrs] + [snrs[-1] + 2.5]
mesh = ax.pcolormesh(x_edges, y_edges, Z, cmap="viridis", norm=norm, shading="flat")
ax.set_xticks(wins); ax.set_xticklabels([f"{w}" for w in wins])
ax.set_yticks(snrs); ax.set_yticklabels([f"{s}" for s in snrs])
ax.set_xlabel("记录窗口 (ns)"); ax.set_ylabel("SNR (dB)")
ax.set_title(f"M4 扫描:等效采样提升比 σ(单通道)/σ(四相位)({repeats} 次 MC)")
cb = fig.colorbar(mesh, ax=ax, label="提升比(对数色标)")
# 文本定位:与 pcolormesh 单元格中心对齐
nx, ny = len(wins), len(snrs)
xc = np.array([(x_edges[j] + x_edges[j + 1]) / 2 for j in range(nx)])
yc = np.array([(y_edges[i] + y_edges[i + 1]) / 2 for i in range(ny)])
for i, s in enumerate(snrs):
for j, w in enumerate(wins):
v = Z[i, j]
if v >= 10:
ax.text(xc[j], yc[i], f"{v:.0f}x", ha="center", va="center", fontsize=8, color="white", fontweight="bold")
elif v >= 2:
ax.text(xc[j], yc[i], f"{v:.1f}x", ha="center", va="center", fontsize=7, color="black")
ax.grid(False)
fig.tight_layout()
# ---------- 图 2:特征曲线(win=200 与 win=400) ----------
fig2, ax2 = plt.subplots(figsize=(7.2, 4.4))
for wi, w in enumerate([200, 400]):
xs = [r["snr_db"] for r in rows if r["window_ns"] == w]
ys = [r["single_rel_std"] for r in rows if r["window_ns"] == w]
yf = [r["fiber_rel_std"] for r in rows if r["window_ns"] == w]
ax2.plot(xs, ys, "o-", color=["#4b2a35", "#8a3b45"][wi],
label=f"单通道 win={w} ns")
ax2.plot(xs, yf, "s--", color=["#2D5F8A", "#6fa3c8"][wi],
label=f"四相位 win={w} ns")
ax2.set_yscale("log")
ax2.set_xlabel("SNR (dB)"); ax2.set_ylabel("τ₂ 相对标准差 (%),对数坐标")
ax2.set_title("M4 扫描:SNR 对 τ₂ 估计稳定性的影响")
ax2.legend(fontsize=8); ax2.grid(alpha=0.3, which="both")
fig2.tight_layout()
run_dir = record.save_run(
runs_dir, "exp06_m4_snr_window_scan", records=[{"scan": rows}],
figures=[("fig1_ratio_heatmap", fig), ("fig2_snr_curves", fig2)],
data_csvs=[("scan", rows)],
notes=("M4 参数扫描:SNR×窗口 对单通道/四相位 τ₂ 相对标准的影响。"
"低 SNR / 短窗口下单通道发散、四相位收敛,复现原项目'单路发散→四路收敛'量级区。"),
)
print(f"\n[exp06] 记录包:{run_dir}")
return run_dir
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--reps", type=int, default=40)
ap.add_argument("--runs-dir", default="runs")
a = ap.parse_args()
run(repeats=a.reps, runs_dir=a.runs_dir)