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

119 lines
5.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.

"""M4 实验:单通道 vs 四相位等效采样的 τ₂ 蒙特卡洛对比 + 参数扫描。
运行:python -m fiber_delay_sim.experiments.exp05_m4_statistics [--repeats 100]
"""
import argparse
import numpy as np
from .. import pipeline
from ..export import record
from ._plot import setup_style
def run(repeats=100, runs_dir="runs"):
plt = setup_style()
cmp = pipeline.run_m4_compare(repeats=repeats, seed=0, snr_db=50.0)
s, f = cmp["single"], cmp["fiber"]
print(f"\n=== M4 单通道 vs 四相位(真值 τ₂ = {cmp['tau_true']} ns,{repeats} 次)===")
for name, st in (("单通道 10ns 直接采样", s), ("四相位 2.5ns 等效采样", f)):
print(f"{name:<22}: mean={st['mean']:.3f} ns rel_std={st['rel_std'] * 100:.2f}% "
f"bias={st.get('bias', 0) * 100:+.2f}% 失败={st['n_failed']}/{st['n']}")
# ---------- 图 1:蒙特卡洛直方图 ----------
fig, ax = plt.subplots(figsize=(7.2, 4.2))
bins = np.linspace(45, 60, 31)
ax.hist(s["tau_hats"], bins=bins, alpha=0.65, color="#C25B2A",
label=f"单通道(σ/τ = {s['rel_std'] * 100:.2f}%)")
ax.hist(f["tau_hats"], bins=bins, alpha=0.65, color="#2D5F8A",
label=f"四相位等效(σ/τ = {f['rel_std'] * 100:.2f}%)")
ax.axvline(cmp["tau_true"], color="k", ls="--", lw=1.5,
label=f"真值 {cmp['tau_true']} ns")
ax.set_xlabel("拟合寿命 τ̂₂ (ns)")
ax.set_ylabel("次数")
ax.set_title(f"M4:τ₂ 蒙特卡洛 {repeats} 次(SNR 50 dB,窗口 400 ns)——等效采样提高估计稳定性")
ax.legend()
ax.grid(alpha=0.3)
# ---------- 图 2:欠采样演示(win=100, snr=40) ----------
cmp_hard = pipeline.run_m4_compare(repeats=repeats, seed=0, snr_db=40.0)
sh, fh = cmp_hard["single"], cmp_hard["fiber"]
fig2, ax2 = plt.subplots(figsize=(7.2, 4.2))
bins2 = np.linspace(20, 85, 41)
ax2.hist(sh["tau_hats"], bins=bins2, alpha=0.5, color="#4b2a35",
label=f"单通道(σ/τ = {sh['rel_std'] * 100:.1f}%),失败 {sh['n_failed']} 次")
ax2.hist(fh["tau_hats"], bins=bins2, alpha=0.6, color="#2D5F8A",
label=f"四相位(σ/τ = {fh['rel_std'] * 100:.1f}%),失败 {fh['n_failed']} 次")
ax2.axvline(cmp["tau_true"], color="k", ls="--", lw=1.5)
ax2.set_xlabel("拟合寿命 τ̂₂ (ns)")
ax2.set_ylabel("次数")
ax2.set_title("M4 低信噪比(SNR 40 dB):单通道发散,四相位收敛")
ax2.legend(fontsize=9)
ax2.grid(alpha=0.3)
# ---------- 图 3:窗口扫描 rel_std ----------
from ..core import acquisition, calibration, fitting, signal, statistics
wins = [60, 100, 150, 200, 300, 400]
rs_s, rs_f = [], []
for w in wins:
p = dict(pipeline.M4_DEFAULTS); p["window_ns"] = float(w)
def g_single(sd):
rng = np.random.default_rng(sd)
sp = signal.resolve_preset("monte_carlo")
t = np.arange(0.0, w + 0.005, 0.01)
y = signal.generate(t, sp)
a = acquisition.run_single_channel(t, y, {"dt_ns": 10, "window_ns": w,
"snr_db": 50, "bits": 14}, rng)
try:
return fitting.fit_double_exp_nls(a["t_samples"], a["y_samples"])["tau2"]
except Exception:
return None
def g_fiber(sd):
rng = np.random.default_rng(sd)
sp = signal.resolve_preset("monte_carlo")
t = np.arange(0.0, w + 0.005, 0.01)
y = signal.generate(t, sp)
a = acquisition.run_multi_channel(t, y, {"delays": [0, 47.5, 95, 142.5],
"dt_ns": 10, "window_ns": w,
"snr_db": 50, "bits": 14}, rng)
c = calibration.calibrate_channels(a["channels"], 10, method="nominal",
do_baseline=False, do_gain=False)
try:
return fitting.fit_double_exp_nls(c["t_rebuilt"], c["y_rebuilt"])["tau2"]
except Exception:
return None
st_s = statistics.monte_carlo(g_single, 30, 0, 52.8)
st_f = statistics.monte_carlo(g_fiber, 30, 0, 52.8)
rs_s.append(st_s["rel_std"] * 100 if st_s["rel_std"] else float("nan"))
rs_f.append(st_f["rel_std"] * 100 if st_f["rel_std"] else float("nan"))
fig3, ax3 = plt.subplots(figsize=(7.2, 4.2))
ax3.plot(wins, rs_s, "o-", color="#4b2a35", label="单通道直接采样")
ax3.plot(wins, rs_f, "s-", color="#2D5F8A", label="四相位等效采样")
ax3.set_xlabel("记录窗口 (ns)")
ax3.set_ylabel("τ₂ 相对标准差 (%)")
ax3.set_title("M4:窗口长度对寿命估计稳定性的影响(SNR 50 dB)")
ax3.legend()
ax3.grid(alpha=0.3)
run_dir = record.save_run(
runs_dir, "exp05_m4_statistics", records=[cmp, cmp_hard],
figures=[("fig1_hist", fig), ("fig2_undersampled", fig2), ("fig3_window_sweep", fig3)],
notes=("M4 统计:主场景(SNR 50 dB)单通道 vs 四相位 τ₂ 蒙特卡洛;"
"欠采样场景(SNR 40 dB);窗口扫描 rel_std。"),
)
print(f"\n[M4] 记录包:{run_dir}")
return run_dir
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--repeats", type=int, default=100)
ap.add_argument("--runs-dir", default="runs")
a = ap.parse_args()
run(repeats=a.repeats, runs_dir=a.runs_dir)