update at 2026-10-12 16:53:40

网站v8修复(时序竞态+M3表格) + exp06 SNR×窗口扫描 + README里程碑更新
This commit is contained in:
douboer
2026-10-12 16:53:41 +08:00
parent 4a734e6299
commit 42cb251061
47 changed files with 29891 additions and 12 deletions

View File

@@ -57,10 +57,10 @@ def cmd_design(args):
def cmd_all(args):
"""M5:一键运行全部实验(M0–M4)并汇总记录包。"""
"""M5:一键运行全部实验(M0–M4 + M4 扫描)并汇总记录包。"""
from .experiments import (exp01_m0_baseline, exp02_fiber_design,
exp03_m2_calibration, exp04_m3_algorithms,
exp05_m4_statistics)
exp05_m4_statistics, exp06_m4_scan)
dirs = []
print("=" * 60)
print("M0 最小程序")
@@ -80,6 +80,9 @@ def cmd_all(args):
print("=" * 60)
print("M4 统计分析")
dirs.append(exp05_m4_statistics.run(repeats=args.repeats, runs_dir=args.runs_dir))
print("=" * 60)
print("M4 补充:SNR×窗口 参数扫描")
dirs.append(exp06_m4_scan.run(repeats=min(args.repeats, 40), runs_dir=args.runs_dir))
print("\n全部完成,记录包:")
for d in dirs:
print(f" - {d}")
@@ -88,10 +91,10 @@ def cmd_all(args):
def cmd_run_one(args):
from .experiments import (exp01_m0_baseline, exp02_fiber_design,
exp03_m2_calibration, exp04_m3_algorithms,
exp05_m4_statistics)
exp05_m4_statistics, exp06_m4_scan)
table = {"m0": exp01_m0_baseline.run, "m1": exp02_fiber_design.run,
"m2": exp03_m2_calibration.run, "m3": exp04_m3_algorithms.run,
"m4": exp05_m4_statistics.run}
"m4": exp05_m4_statistics.run, "scan": exp06_m4_scan.run}
if args.which not in table:
print(f"未知实验 {args.which},可选:{list(table)}")
return
@@ -107,6 +110,8 @@ def cmd_run_one(args):
table["m3"](seeds=args.seeds, runs_dir=args.runs_dir)
elif args.which == "m4":
table["m4"](repeats=args.repeats, runs_dir=args.runs_dir)
elif args.which == "scan":
table["scan"](repeats=min(args.repeats, 40), runs_dir=args.runs_dir)
def main(argv=None):
@@ -135,8 +140,8 @@ def main(argv=None):
p1.add_argument("--runs-dir", default="runs")
p1.set_defaults(func=cmd_design)
p2 = sub.add_parser("run", help="运行单个实验:m0/m1/m2/m3/m4")
p2.add_argument("which", choices=["m0", "m1", "m2", "m3", "m4"])
p2 = sub.add_parser("run", help="运行单个实验:m0/m1/m2/m3/m4/scan")
p2.add_argument("which", choices=["m0", "m1", "m2", "m3", "m4", "scan"])
p2.add_argument("--tau", type=float, default=52.8)
p2.add_argument("--window-ns", type=float, default=400.0)
p2.add_argument("--snr-db", type=float, default=50.0)

View File

@@ -0,0 +1,107 @@
"""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)

View File

@@ -40,11 +40,13 @@ def git_hash():
return "unversioned"
def save_run(runs_dir, name, records, figures=None, notes="", seed=None, extra_meta=None):
def save_run(runs_dir, name, records, figures=None, notes="", seed=None, extra_meta=None,
data_csvs=None):
"""落盘一个记录包。
records: dict 或 list[dict],每个含 meta/data 字段(pipeline 输出);
figures: list[(filename, matplotlib.figure)]。
figures: list[(filename, matplotlib.figure)];
data_csvs: list[(filename, list[dict])]——任意键值表写入 data/(扫描数据等)。
返回记录包目录。
"""
ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
@@ -79,7 +81,8 @@ def save_run(runs_dir, name, records, figures=None, notes="", seed=None, extra_m
if k in ("fit", "tau_hat", "tau_true", "rel_error", "n_samples",
"sigma", "mean", "std", "rel_std", "bias", "tau_hats",
"uniformity", "sorted_phases_ns", "channels", "construction",
"target_phases_ns", "is_uniform_grid", "recommended")}
"target_phases_ns", "is_uniform_grid", "recommended",
"scan", "single_rel_std", "fiber_rel_std", "ratio")}
results.append(r)
# 采样点 CSV
if "t_samples" in rec:
@@ -99,6 +102,15 @@ def save_run(runs_dir, name, records, figures=None, notes="", seed=None, extra_m
fig.savefig(os.path.join(run_dir, "figures", f"{fname}.svg"))
fig.savefig(os.path.join(run_dir, "figures", f"{fname}.png"), dpi=150)
for fname, rows in (data_csvs or []):
if not rows:
continue
path = os.path.join(run_dir, "data", f"{fname}.csv")
with open(path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
with open(os.path.join(run_dir, "README.md"), "w") as f:
f.write(f"# 记录包:{name}\n\n{notes}\n\n"
f"- 运行时间:{meta['created']}\n"