Files
chenproject/fiber_delay_sim/experiments/exp01_m0_baseline.py
2026-10-12 14:26:51 +08:00

112 lines
5.1 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.

"""M0 基准实验:单指数信号 + 10ns 直接采样 + 噪声 + NLS 寿命拟合。
场景 A:理想无噪 → 拟合应恢复设定寿命(M0 验收①,对应原项目"标准拟合"基准);
场景 B:SNR 50 dB + 12bit 量化,重复 N 次 → τ̂ 分布(M0 验收③)。
运行:python -m fiber_delay_sim.experiments.exp01_m0_baseline [--repeats 20] [--seed 42]
"""
import argparse
import numpy as np
from .. import pipeline
from ..export import record
from ._plot import setup_style
def run(tau=52.8, window_ns=400.0, snr_db=50.0, bits=12, repeats=20, seed=42, runs_dir="runs"):
plt = setup_style()
# ---------- 场景 A:理想无噪 ----------
ideal_params = {"preset": "single", "tau": tau, "snr_db": None, "bits": None,
"window_ns": window_ns}
rec_ideal = pipeline.run_m0(ideal_params, seed=seed)
# ---------- 场景 B:加噪重复 ----------
noisy_params = {"preset": "single", "tau": tau, "snr_db": snr_db, "bits": bits,
"window_ns": window_ns}
rec_noise = pipeline.run_m0(noisy_params, seed=seed)
reps = pipeline.run_m0_repeats(noisy_params, repeats=repeats, seed=seed)
# ---------- 图 1:理想采样与拟合(第一张拟合图) ----------
fig1, ax = plt.subplots(figsize=(7, 4.2))
ax.plot(rec_ideal["t_cont"], rec_ideal["y_cont"], "-", color="#9aa5b1", lw=1.2,
label="连续信号(真值)")
ax.plot(rec_ideal["t_samples"], rec_ideal["y_samples"], "o", color="#2D5F8A", ms=6,
label=f"10 ns 直接采样({rec_ideal['n_samples']} 点)")
t_fit = rec_ideal["t_samples"]
f = rec_ideal["fit"]
ax.plot(t_fit, f["A"] * np.exp(-t_fit / f["tau"]) + f["B"], "r--", lw=1.5,
label=f"NLS 拟合:τ̂ = {f['tau']:.4f} ns")
ax.set_xlabel("时间 (ns)")
ax.set_ylabel("归一化强度")
ax.set_title(f"M0 理想无噪基准:设定 τ = {tau} ns,恢复偏差 "
f"{rec_ideal['rel_error']:.2e}(相对)")
ax.legend()
ax.grid(alpha=0.3)
# ---------- 图 2:加噪单次 ----------
fig2, ax = plt.subplots(figsize=(7, 4.2))
ax.plot(rec_noise["t_cont"], rec_noise["y_cont"], "-", color="#9aa5b1", lw=1.2,
label="连续信号(真值)")
ax.plot(rec_noise["t_samples"], rec_noise["y_samples"], "o", color="#C25B2A", ms=5,
label=f"采样点(SNR {snr_db} dB,{rec_noise['bits']} bit)")
fn = rec_noise["fit"]
ax.plot(t_fit, fn["A"] * np.exp(-t_fit / fn["tau"]) + fn["B"], "r--", lw=1.5,
label=f"NLS 拟合:τ̂ = {fn['tau']:.3f} ns")
ax.set_xlabel("时间 (ns)")
ax.set_ylabel("归一化强度")
ax.set_title(f"M0 加噪单次:SNR = {snr_db} dB,12 bit 量化")
ax.legend()
ax.grid(alpha=0.3)
# ---------- 图 3:重复实验 τ̂ 分布 ----------
fig3, ax = plt.subplots(figsize=(7, 4.2))
ax.hist(reps["tau_hats"], bins=max(10, repeats // 2), color="#2D5F8A",
alpha=0.75, edgecolor="white")
ax.axvline(reps["tau_true"], color="#C25B2A", ls="--", lw=2,
label=f"真值 τ = {reps['tau_true']:.1f} ns")
ax.axvline(reps["mean"], color="#1A5276", ls=":", lw=2,
label=f"均值 {reps['mean']:.3f} ns")
ax.set_xlabel("拟合寿命 τ̂ (ns)")
ax.set_ylabel("次数")
ax.set_title(f"M0 重复 {repeats} 次:相对标准差 {reps['rel_std'] * 100:.2f}%,"
f"偏差 {reps['bias'] * 100:+.2f}%")
ax.legend()
ax.grid(alpha=0.3)
# ---------- 落盘记录包 ----------
run_dir = record.save_run(
runs_dir, "exp01_m0_baseline",
records=[rec_ideal, rec_noise, reps],
figures=[("fig1_ideal_fit", fig1), ("fig2_noisy_fit", fig2),
("fig3_repeat_hist", fig3)],
notes=(f"M0 基准:①理想无噪恢复 τ={tau} ns(偏差 {rec_ideal['rel_error']:.2e});"
f"②SNR {snr_db} dB 重复 {repeats} 次分布:均值 {reps['mean']:.3f} ns、"
f"相对标准差 {reps['rel_std'] * 100:.2f}%。"),
seed=seed,
)
print(f"[M0] 理想无噪:τ̂ = {rec_ideal['fit']['tau']:.6f} ns "
f"(设定 {tau},相对偏差 {rec_ideal['rel_error']:.2e})")
print(f"[M0] 加噪单次:τ̂ = {rec_noise['fit']['tau']:.3f} ns")
print(f"[M0] 重复 {repeats} 次:均值 {reps['mean']:.3f} ns,"
f"σ(τ̂)/τ = {reps['rel_std'] * 100:.2f}%,bias = {reps['bias'] * 100:+.2f}%")
print(f"[M0] 记录包:{run_dir}")
return run_dir
if __name__ == "__main__":
ap = argparse.ArgumentParser(description="M0 基准实验")
ap.add_argument("--tau", type=float, default=52.8)
ap.add_argument("--window-ns", type=float, default=400.0)
ap.add_argument("--snr-db", type=float, default=50.0)
ap.add_argument("--bits", type=int, default=12)
ap.add_argument("--repeats", type=int, default=20)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--runs-dir", default="runs")
a = ap.parse_args()
run(tau=a.tau, window_ns=a.window_ns, snr_db=a.snr_db, bits=a.bits,
repeats=a.repeats, seed=a.seed, runs_dir=a.runs_dir)