update at 2026-10-12 14:26:51
This commit is contained in:
1
fiber_delay_sim/experiments/__init__.py
Normal file
1
fiber_delay_sim/experiments/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""实验脚本(本地层:可使用 matplotlib;每个脚本产出论文/教学的一个完整记录包)。"""
|
||||
BIN
fiber_delay_sim/experiments/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
fiber_delay_sim/experiments/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
fiber_delay_sim/experiments/__pycache__/_plot.cpython-312.pyc
Normal file
BIN
fiber_delay_sim/experiments/__pycache__/_plot.cpython-312.pyc
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
13
fiber_delay_sim/experiments/_plot.py
Normal file
13
fiber_delay_sim/experiments/_plot.py
Normal file
@@ -0,0 +1,13 @@
|
||||
"""matplotlib 绘图样式(本地层专用)。"""
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def setup_style():
|
||||
plt.rcParams["font.sans-serif"] = [
|
||||
"PingFang SC", "Hiragino Sans GB", "Arial Unicode MS", "SimHei", "sans-serif",
|
||||
]
|
||||
plt.rcParams["axes.unicode_minus"] = False
|
||||
plt.rcParams["figure.dpi"] = 120
|
||||
plt.rcParams["savefig.bbox"] = "tight"
|
||||
return plt
|
||||
111
fiber_delay_sim/experiments/exp01_m0_baseline.py
Normal file
111
fiber_delay_sim/experiments/exp01_m0_baseline.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""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)
|
||||
121
fiber_delay_sim/experiments/exp02_fiber_design.py
Normal file
121
fiber_delay_sim/experiments/exp02_fiber_design.py
Normal file
@@ -0,0 +1,121 @@
|
||||
"""M1 光纤设计实验:名义四组 → 延时/相位表 + 反向设计 + 相位图。
|
||||
|
||||
运行:python -m fiber_delay_sim.experiments.exp02_fiber_design
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..core import fiber
|
||||
from ..export import record
|
||||
from ._plot import setup_style
|
||||
|
||||
|
||||
def _print_table(title, rows, header):
|
||||
print(f"\n=== {title} ===")
|
||||
print(" | ".join(f"{h:>12}" for h in header))
|
||||
for r in rows:
|
||||
print(" | ".join(f"{c:>12}" if isinstance(c, str) else f"{c:>12.4f}" for c in r))
|
||||
|
||||
|
||||
def run(runs_dir="runs"):
|
||||
plt = setup_style()
|
||||
|
||||
# ---------- 正向:名义四组(设计延时精确值) ----------
|
||||
fwd = fiber.forward_design(delays_ns=fiber.NOMINAL_DELAYS_NS)
|
||||
rows = []
|
||||
for ch in fwd["channels"]:
|
||||
rows.append((f"CH{ch['index'] + 1}", ch["delay_ns"], ch["phase_ns"],
|
||||
fiber.NOMINAL_LENGTHS_M[ch["index"]], ch["length_m"]))
|
||||
_print_table("名义四组:设计延时 / 相位 / 长度", rows,
|
||||
["通道", "设计延时 ns", "相位 ns", "名义长度 m", "反算长度 m"])
|
||||
u = fwd["uniformity"]
|
||||
print(f"排序后等效网格:{fwd['sorted_phases_ns']} ns"
|
||||
f"(理想步长 {u['ideal_step_ns']} ns,最大间隔偏差 {u['max_gap_dev_ns']:.3g} ns)")
|
||||
|
||||
# ---------- 反向设计:目标 0/2.5/5/7.5 ----------
|
||||
targets = [0.0, 2.5, 5.0, 7.5]
|
||||
inv = fiber.inverse_design(targets)
|
||||
assert inv["is_uniform_grid"] and inv["recommended"]
|
||||
rec_rows = [(e["phase_ns"], e["k"], e["delay_ns"], e["length_m"]) for e in inv["recommended"]]
|
||||
_print_table("反向设计推荐解(目标相位 0/2.5/5/7.5 ns)", rec_rows,
|
||||
["目标相位 ns", "通道序 k", "延时 ns", "长度 m"])
|
||||
print(f"构造式:{inv['construction']}")
|
||||
|
||||
# ---------- 图 1:一个采样周期内的相位位置 ----------
|
||||
fig1, ax = plt.subplots(figsize=(7, 3.2))
|
||||
colors = ["#2D5F8A", "#C25B2A", "#2A6B5A", "#6B2A35"]
|
||||
for i, ch in enumerate(fwd["channels"]):
|
||||
ax.plot([ch["phase_ns"]], [1], "o", ms=12, color=colors[i % 4])
|
||||
ax.annotate(f"CH{ch['index'] + 1}\nφ={ch['phase_ns']:.1f} ns",
|
||||
(ch["phase_ns"], 1), textcoords="offset points",
|
||||
xytext=(0, 14 + 12 * (i % 2)), ha="center", fontsize=9)
|
||||
ax.axhline(1, color="#9aa5b1", lw=1)
|
||||
for x in np.arange(0, 11, 2.5):
|
||||
ax.axvline(x, color="#d8dee5", lw=0.8, ls="--")
|
||||
ax.set_xlim(-1, 11)
|
||||
ax.set_ylim(0.6, 1.9)
|
||||
ax.set_yticks([])
|
||||
ax.set_xticks(np.arange(0, 11, 2.5))
|
||||
ax.set_xlabel("采样周期内相位 (ns)")
|
||||
ax.set_title("四路光纤延时在一个 10 ns 采样周期内的相位位置(0 / 2.5 / 5.0 / 7.5 ns)")
|
||||
ax.grid(alpha=0.2)
|
||||
|
||||
# ---------- 图 2:相位圆图 ----------
|
||||
fig2 = plt.figure(figsize=(5.2, 5.2))
|
||||
ax2 = fig2.add_subplot(111, projection="polar")
|
||||
for i, ch in enumerate(fwd["channels"]):
|
||||
theta = 2 * np.pi * ch["phase_ns"] / fiber.DT_DEFAULT
|
||||
ax2.plot([theta], [1], "o", ms=14, color=colors[i % 4])
|
||||
ax2.annotate(f"CH{ch['index'] + 1}", (theta, 1.15), ha="center",
|
||||
textcoords="data", fontsize=11)
|
||||
ax2.set_yticks([])
|
||||
ax2.set_xticks(2 * np.pi * np.arange(0, 10, 2.5) / 10)
|
||||
ax2.set_xticklabels(["0 ns", "2.5 ns", "5.0 ns", "7.5 ns"])
|
||||
ax2.set_title("相位圆图:10 ns 周期内的等效采样相位", pad=18)
|
||||
|
||||
# ---------- 图 3:记录时间轴上的四路延时片段示意 ----------
|
||||
fig3, ax3 = plt.subplots(figsize=(7.2, 3.6))
|
||||
for i, ch in enumerate(fwd["channels"]):
|
||||
ax3.plot([ch["delay_ns"], ch["delay_ns"] + 20], [i, i], "-", lw=3,
|
||||
color=colors[i % 4], solid_capstyle="butt")
|
||||
ax3.annotate(f"CH{ch['index'] + 1}: δ={ch['delay_ns']:.1f} ns (L={fiber.NOMINAL_LENGTHS_M[ch['index']]:.2f} m)",
|
||||
(ch["delay_ns"], i), textcoords="offset points", xytext=(2, -14),
|
||||
fontsize=9)
|
||||
ax3.set_xlim(-5, 175)
|
||||
ax3.set_ylim(-0.8, 3.8)
|
||||
ax3.set_yticks([])
|
||||
ax3.set_xlabel("记录时间轴 (ns)")
|
||||
ax3.set_title("四路延时片段在记录时间轴上的定位(片段间隔约 47.5 ns,相位错开 2.5 ns)")
|
||||
ax3.grid(alpha=0.25)
|
||||
|
||||
# ---------- 记录包 ----------
|
||||
pack = {
|
||||
"meta": {"experiment": "exp02_fiber_design",
|
||||
"data_origin": "software-simulated", "params": None},
|
||||
"channels": fwd["channels"],
|
||||
"sorted_phases_ns": fwd["sorted_phases_ns"],
|
||||
"uniformity": u,
|
||||
"target_phases_ns": inv["target_phases_ns"],
|
||||
"is_uniform_grid": inv["is_uniform_grid"],
|
||||
"recommended": inv["recommended"],
|
||||
"construction": inv["construction"],
|
||||
}
|
||||
run_dir = record.save_run(
|
||||
runs_dir, "exp02_fiber_design", records=[pack],
|
||||
figures=[("fig1_phase_positions", fig1), ("fig2_phase_circle", fig2),
|
||||
("fig3_delay_segments", fig3)],
|
||||
notes=("M1 光纤设计:名义四组 0/9.70/19.40/29.10 m → 延时 0/47.5/95/142.5 ns → "
|
||||
"相位 0/2.5/5.0/7.5 ns(均匀网格,最大间隔偏差 "
|
||||
f"{u['max_gap_dev_ns']:.3g} ns);反向设计复现原项目方案。"),
|
||||
)
|
||||
print(f"\n[M1] 记录包:{run_dir}")
|
||||
return run_dir
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description="M1 光纤设计实验")
|
||||
ap.add_argument("--runs-dir", default="runs")
|
||||
a = ap.parse_args()
|
||||
run(runs_dir=a.runs_dir)
|
||||
Reference in New Issue
Block a user