update at 2026-10-12 16:25:51

This commit is contained in:
douboer
2026-10-12 16:25:51 +08:00
parent db63516781
commit a484c7914f
67 changed files with 30357 additions and 193 deletions

View File

@@ -5,5 +5,5 @@
(约束见 docs/实现方案.md §5.1)。
"""
__version__ = "0.1.0"
ALGO_VERSION = "M0+M1"
__version__ = "0.5.0"
ALGO_VERSION = "M0-M4"

Binary file not shown.

View File

@@ -56,6 +56,59 @@ def cmd_design(args):
exp02_fiber_design.run(runs_dir=args.runs_dir)
def cmd_all(args):
"""M5:一键运行全部实验(M0–M4)并汇总记录包。"""
from .experiments import (exp01_m0_baseline, exp02_fiber_design,
exp03_m2_calibration, exp04_m3_algorithms,
exp05_m4_statistics)
dirs = []
print("=" * 60)
print("M0 最小程序")
dirs.append(exp01_m0_baseline.run(tau=args.tau, window_ns=args.window_ns,
snr_db=args.snr_db, bits=args.bits,
repeats=args.repeats, seed=args.seed,
runs_dir=args.runs_dir))
print("=" * 60)
print("M1 光纤设计")
dirs.append(exp02_fiber_design.run(runs_dir=args.runs_dir))
print("=" * 60)
print("M2 误差与校准")
dirs.append(exp03_m2_calibration.run(seed=args.seed, runs_dir=args.runs_dir))
print("=" * 60)
print("M3 算法对比")
dirs.append(exp04_m3_algorithms.run(seeds=args.seeds, runs_dir=args.runs_dir))
print("=" * 60)
print("M4 统计分析")
dirs.append(exp05_m4_statistics.run(repeats=args.repeats, runs_dir=args.runs_dir))
print("\n全部完成,记录包:")
for d in dirs:
print(f" - {d}")
def cmd_run_one(args):
from .experiments import (exp01_m0_baseline, exp02_fiber_design,
exp03_m2_calibration, exp04_m3_algorithms,
exp05_m4_statistics)
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}
if args.which not in table:
print(f"未知实验 {args.which},可选:{list(table)}")
return
if args.which == "m0":
table["m0"](tau=args.tau, window_ns=args.window_ns, snr_db=args.snr_db,
bits=args.bits, repeats=args.repeats, seed=args.seed,
runs_dir=args.runs_dir)
elif args.which == "m1":
table["m1"](runs_dir=args.runs_dir)
elif args.which == "m2":
table["m2"](seed=args.seed, runs_dir=args.runs_dir)
elif args.which == "m3":
table["m3"](seeds=args.seeds, runs_dir=args.runs_dir)
elif args.which == "m4":
table["m4"](repeats=args.repeats, runs_dir=args.runs_dir)
def main(argv=None):
ap = argparse.ArgumentParser(prog="fiber_delay_sim",
description="光纤延时等效采样教学实验仿真软件")
@@ -82,6 +135,29 @@ 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.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)
p2.add_argument("--bits", type=int, default=12)
p2.add_argument("--repeats", type=int, default=100)
p2.add_argument("--seeds", type=int, default=8)
p2.add_argument("--seed", type=int, default=42)
p2.add_argument("--runs-dir", default="runs")
p2.set_defaults(func=cmd_run_one)
p3 = sub.add_parser("all", help="M5:一键运行全部实验(M0–M4)")
p3.add_argument("--tau", type=float, default=52.8)
p3.add_argument("--window-ns", type=float, default=400.0)
p3.add_argument("--snr-db", type=float, default=50.0)
p3.add_argument("--bits", type=int, default=12)
p3.add_argument("--repeats", type=int, default=100)
p3.add_argument("--seeds", type=int, default=8)
p3.add_argument("--seed", type=int, default=42)
p3.add_argument("--runs-dir", default="runs")
p3.set_defaults(func=cmd_all)
args = ap.parse_args(argv)
args.func(args)

View File

@@ -1,5 +1,5 @@
"""算法核心层:signal / fiber / acquisition / fitting(全部 Pyodide 兼容)。"""
"""算法核心层:signal / fiber / acquisition / calibration / fitting / statistics(全部 Pyodide 兼容)。"""
from . import signal, fiber, acquisition, fitting
from . import signal, fiber, acquisition, calibration, fitting, statistics
__all__ = ["signal", "fiber", "acquisition", "fitting"]
__all__ = ["signal", "fiber", "acquisition", "calibration", "fitting", "statistics"]

View File

@@ -99,3 +99,81 @@ def run_single_channel(t_cont, y_cont, params, rng):
"jitter_ns": jitter,
"bandwidth_sigma_ns": float(p.get("bandwidth_sigma_ns", 0.0) or 0.0),
}
def _interp_signal(s_times, t_cont, y_cont):
"""在等效时间 s 处取值;s<0(信号未到达)按 0 处理(触发前无信号)。"""
s = np.asarray(s_times, dtype=float)
y = np.interp(s, t_cont, y_cont) # 先按边界插值(s<0 → y(0))
y = np.where(s < 0, 0.0, y) # s<0 → 0(激发关断前无荧光)
return y
def run_multi_channel(t_cont, y_cont, params, rng):
"""四通道光纤延时等效采样(M2 起)。
物理模型:四路信号副本经光纤延时 δk;同一 ADC 从触发时刻起以 Δt 采样,
第 k 路第 m 个样本采样到的是 x(t_m − δk),等效时间 s = t_m − δk。
params(在 M0 单通道参数基础上增加):
delays 名义延时列表(ns),如 [0, 47.5, 95.0, 142.5]
gain_errors 各通道相对增益误差(0 为理想)
delay_errors 各通道延时误差(ns,0 为理想)
baselines 各通道基线偏置(相对峰值,0 为理想)
返回 dict(纯数据)。
"""
p = dict(params)
t_cont = np.asarray(t_cont, dtype=float)
y_cont = np.asarray(y_cont, dtype=float)
delays = [float(d) for d in p["delays"]]
n_ch = len(delays)
gain_err = p.get("gain_errors", [0.0] * n_ch)
delay_err = p.get("delay_errors", [0.0] * n_ch)
base_frac = p.get("baselines", [0.0] * n_ch)
dt = float(p.get("dt_ns", 10.0))
t0 = float(p.get("t0_ns", 0.0))
window = float(p.get("window_ns", t_cont[-1] - t_cont[0]))
n_samples = int(round(window / dt))
y_bw = gaussian_response(t_cont, y_cont, p.get("bandwidth_sigma_ns", 0.0))
peak = float(np.max(y_bw)) if np.max(y_bw) > 0 else 1.0
snr_db = p.get("snr_db")
sigma = snr_to_sigma(snr_db, peak) if snr_db is not None else 0.0
bits = p.get("bits")
ts_m = t0 + dt * np.arange(n_samples) # ADC 绝对采样时刻
channels = []
for k in range(n_ch):
d_eff = delays[k] + delay_err[k] # 实际延时(含误差)
s = ts_m - d_eff # 等效时间(相对触发)
y_clean = _interp_signal(s, t_cont, y_bw)
y_clean = y_clean * (1.0 + gain_err[k]) + base_frac[k] * peak
y_meas = y_clean + (rng.normal(0.0, sigma, size=n_samples) if sigma > 0 else 0.0)
if bits is not None:
fs = p.get("fullscale") or 2.0 * peak
y_meas = quantize_adc(y_meas, bits, fs)
channels.append({
"index": k,
"delay_ns": delays[k],
"delay_eff_ns": d_eff,
"gain": 1.0 + gain_err[k],
"baseline": base_frac[k] * peak,
"t_adc": ts_m,
"s_equiv": s, # 等效时间(校准前:用设计延时)
"y_clean": y_clean,
"y_samples": y_meas,
})
return {
"n_channels": n_ch,
"dt_ns": dt,
"t0_ns": t0,
"n_samples": n_samples,
"sigma": sigma,
"snr_db": snr_db,
"bits": bits,
"peak": peak,
"channels": channels,
}

View File

@@ -0,0 +1,154 @@
"""通道校准:基线扣除、增益归一化、延时校准与时间重建(仅依赖 numpy)。
校准三步对应 docs/实现方案.md §7.3:
1. 基线扣除(尾段均值 / 显式传入);
2. 增益归一化(参考通道峰值对齐);
3. 延时校准——两种方法供教学比较:
- "标定值":使用外部标定得到的延时(模拟器可提供真实延时 + 可调标定残差,
对应原项目误差机制表中"延时标定误差");
- "互相关":仅用采样数据互相关估计(只能分辨 Δt 整数周期,
亚采样相位无法恢复——教学点:互相关校准的粒度限制)。
"""
import numpy as np
def estimate_baseline(y, tail_frac=0.2):
"""尾段均值估计基线(若衰减尾部未归零则高估——教学点)。"""
y = np.asarray(y, dtype=float)
tail_n = max(1, int(len(y) * tail_frac))
return float(np.mean(y[-tail_n:]))
def subtract_baseline(y, baseline=None, tail_frac=0.2):
"""扣除基线;返回 (去基线序列, 基线值)。"""
b = baseline if baseline is not None else estimate_baseline(y, tail_frac)
return np.asarray(y, dtype=float) - b, float(b)
def normalize_gain(y, ref_peak):
"""以参考峰值对齐通道幅度;返回 (归一化序列, 增益系数)。"""
y = np.asarray(y, dtype=float)
peak = float(np.max(np.abs(y)))
if peak <= 0:
return y, 1.0
g = ref_peak / peak
return y * g, g
def estimate_delay_cross_corr(ref_y, sig_y, dt_ns):
"""互相关估计相对延时:只能得到 Δt 整数倍的滞(教学点)。"""
ref = np.asarray(ref_y, dtype=float)
sig = np.asarray(sig_y, dtype=float)
m = min(len(ref), len(sig))
cc = np.correlate(sig[:m], ref[:m], mode="full")
lag = int(np.argmax(cc) - (m - 1))
return float(lag) * dt_ns, int(lag)
def rebuild(t_adc, y, delay_used, dt_ns):
"""时间重建(Redis):u = t_adc − delay,合并后按时间排序。
delay_used 为每通道使用的延时(名义 / 标定 / 互相关估计)。
"""
t_all, y_all = [], []
for k in range(len(t_adc)):
u = np.asarray(t_adc[k], dtype=float) - float(delay_used[k])
mask = u >= 0
t_all.append(u[mask])
y_all.append(np.asarray(y[k], dtype=float)[mask])
if not t_all:
return np.array([]), np.array([])
t_re = np.concatenate(t_all)
y_re = np.concatenate(y_all)
order = np.argsort(t_re)
return t_re[order], y_re[order]
def calibrate_channels(channels, dt_ns, delay_est_ns=None, method="nominal",
tail_frac=0.2, do_baseline=True, do_gain=True,
baseline_known=None):
"""三步校准(基线 → 增益 → 延时)并重建统一时间轴。
参数:
channels acquisition.run_multi_channel 返回的 channels 列表(dict)
dt_ns 采样间隔
delay_est_ns 各通道校准延时(长度=通道数);None 时按 method 选择
method "nominal"(设计延时)/ "cross_corr"(互相关整数粒度)
do_baseline 是否做基线扣除(False → 原始信号直接重建,模拟"不校准")
do_gain 是否做增益归一(False → 不归一)
baseline_known 每通道已知基线(None → 尾段估计;传 0 表示"标定已知无基线")
返回 dict:baselines、gains、delay_used_ns、t_rebuilt、y_rebuilt、
n_points、continuity(相邻点跳变统计)。
"""
n = len(channels)
t_adc = [ch["t_adc"] for ch in channels]
y_meas = [ch["y_samples"] for ch in channels]
# 1) 基线
baselines = []
debased = []
for k, y in enumerate(y_meas):
if not do_baseline:
baselines.append(0.0)
debased.append(np.asarray(y, dtype=float))
elif baseline_known is not None:
b = float(baseline_known[k])
baselines.append(b)
debased.append(np.asarray(y, dtype=float) - b)
else:
d, b = subtract_baseline(y, tail_frac=tail_frac)
baselines.append(b)
debased.append(d)
# 2) 增益归一化(参考通道 = index 0)
ref_peak = float(np.max(np.abs(debased[0]))) if n else 1.0
gains = []
normed = []
for d in debased:
if not do_gain:
gains.append(1.0)
normed.append(d)
else:
g, fact = normalize_gain(d, ref_peak)
gains.append(fact)
normed.append(g)
# 3) 延时
if delay_est_ns is not None:
d_used = [float(v) for v in delay_est_ns]
elif method == "cross_corr":
d_used = [0.0]
for k in range(1, n):
d, _ = estimate_delay_cross_corr(normed[0], normed[k], dt_ns)
d_used.append(d)
else: # nominal:各通道设计延时(含真实误差需另行传入才体现)
d_used = [float(ch["delay_ns"]) for ch in channels]
# 4) 重建
t_re, y_re = rebuild(t_adc, normed, d_used, dt_ns)
return {
"n_channels": n,
"baselines": baselines,
"gains": gains,
"delay_used_ns": d_used,
"t_rebuilt": t_re,
"y_rebuilt": y_re,
"n_points": int(len(t_re)),
"continuity": continuity_metrics(t_re, y_re),
}
def continuity_metrics(t, y):
"""重建曲线不连续度:相邻点归一化跳变的最大/平均统计。"""
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
if len(t) < 2:
return {"max_jump": 0.0, "mean_jump": 0.0, "rms_jump": 0.0}
amp = float(np.max(np.abs(y))) if np.max(np.abs(y)) > 0 else 1.0
jumps = np.abs(np.diff(y)) / amp
return {
"max_jump": float(np.max(jumps)),
"mean_jump": float(np.mean(jumps)),
"rms_jump": float(np.sqrt(np.mean(jumps ** 2))),
}

View File

@@ -0,0 +1,88 @@
"""统计分析:蒙特卡洛重复、参数扫描、置信区间、失败率(仅依赖 numpy/scipy)。
对应 docs/实现方案.md §7.6 与 §8。
gen_fn 为可调用对象:gen_fn(seed, **params) -> tau_hat(float),
由调用方(pipeline)注入,保证本模块与具体模型解耦(Pyodide 兼容)。
"""
import numpy as np
def failure_rate(tau_hats, tau_true, tol=0.05):
"""失败率:|τ̂−τ|/τ > tol 的比例。"""
arr = np.asarray(tau_hats, dtype=float)
if tau_true is None or tau_true == 0 or len(arr) == 0:
return 0.0
rel = np.abs(arr - tau_true) / tau_true
return float(np.mean(rel > tol))
def confidence_interval(tau_hats, level=0.95):
"""正态近似置信区间(大样本/教学用);附标准差。"""
arr = np.asarray(tau_hats, dtype=float)
n = len(arr)
if n < 2:
return {"mean": None, "std": None, "ci_lo": None, "ci_hi": None}
mean = float(np.mean(arr))
std = float(np.std(arr, ddof=1))
z = 1.96 if level >= 0.95 else 1.645
return {
"mean": mean,
"std": std,
"ci_lo": float(mean - z * std / np.sqrt(n)),
"ci_hi": float(mean + z * std / np.sqrt(n)),
"level": level,
}
def monte_carlo(gen_fn, repeats=200, seed=0, tau_true=None, tol=0.05):
"""蒙特卡洛重复:不同种子运行 repeats 次,统计 τ̂ 分布。
gen_fn 返回 None 表示本次拟合失败(欠采样/不收敛),计入 n_failed 跳过。
"""
tau_hats = []
n_failed = 0
for i in range(int(repeats)):
v = gen_fn(seed + i)
if v is None:
n_failed += 1
else:
tau_hats.append(float(v))
n_ok = len(tau_hats)
result = {
"n": int(repeats),
"n_ok": n_ok,
"n_failed": n_failed,
"failure_rate_fit": n_failed / int(repeats) if repeats else 0.0,
"tau_hats": tau_hats,
"tau_true": tau_true,
}
if n_ok >= 2:
ci = confidence_interval(tau_hats)
result.update({
"mean": ci["mean"],
"std": ci["std"],
"rel_std": (ci["std"] / ci["mean"]) if ci["mean"] else None,
"ci_lo": ci["ci_lo"],
"ci_hi": ci["ci_hi"],
})
if tau_true is not None:
result["bias"] = (result["mean"] - tau_true) / tau_true
result["failure_rate"] = failure_rate(tau_hats, tau_true, tol)
return result
def sweep(gen_fn, param_name, values, repeats=20, seed=0, tau_true=None, tol=0.05):
"""参数扫描:对每个参数值做蒙特卡洛(小样本),输出趋势表。
返回 [{param, mean, std, rel_std, bias, failure_rate}, ...]。
"""
rows = []
for i, v in enumerate(values):
st = monte_carlo(gen_fn, repeats=repeats, seed=seed + i * 1000,
tau_true=tau_true, tol=tol)
row = {param: float(v)}
for key in ("mean", "std", "rel_std", "bias", "failure_rate", "tau_true"):
row[key] = st.get(key)
rows.append(row)
return {"param": param, "values": [float(v) for v in values], "rows": rows}

View File

@@ -0,0 +1,80 @@
"""M2 实验:四通道误差注入与校准(raw / 基线+增益校准 / 完整校准 三方案对比)。
运行:python -m fiber_delay_sim.experiments.exp03_m2_calibration [--seed 42]
"""
import argparse
import numpy as np
from .. import pipeline
from ..export import record
from ._plot import setup_style
def run(seed=42, runs_dir="runs"):
plt = setup_style()
rec = pipeline.run_m2({"snr_db": 60.0, "bits": 14}, seed=seed)
tau_true = rec["tau_true"]
# ---------- 图 1:三方案重建曲线 vs 理论 ----------
fig, ax = plt.subplots(figsize=(8, 4.6))
schemes = [("raw", "不校准", "#C25B2A", "o"),
("nominal", "基线+增益校准", "#6B2A35", "s"),
("calibrated", "完整校准", "#2D5F8A", "^")]
for key, label, color, mk in schemes:
d = rec[key]
ax.plot(d["t"], d["y"], mk, ms=3, color=color, label=label, alpha=0.75)
t_th = np.arange(0, 400, 0.5)
ax.plot(t_th, np.exp(-t_th / tau_true), "k-", lw=1.2,
label=f"理论 I(t)=e^(−t/{tau_true:g})")
ax.set_xlim(0, 180)
ax.set_xlabel("等效时间 u (ns)")
ax.set_ylabel("归一化强度")
ax.set_title("M2:误差注入后三种处理方案的重建曲线(0–180 ns)")
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
# ---------- 图 2:连续度与 τ̂ 对比柱状 ----------
fig2, axes = plt.subplots(1, 2, figsize=(8.5, 3.8))
names = ["raw", "nominal", "calibrated"]
labels = ["不校准", "基线+增益", "完整校准"]
jumps = [rec[n]["continuity"]["mean_jump"] for n in names]
errs = [abs(rec[n]["tau_hat"] - tau_true) / tau_true * 100 for n in names]
axes[0].bar(labels, jumps, color=["#C25B2A", "#6B2A35", "#2D5F8A"])
axes[0].set_ylabel("重建连续度 mean_jump")
axes[0].set_title("校准降低通道断层")
axes[1].bar(labels, errs, color=["#C25B2A", "#6B2A35", "#2D5F8A"])
axes[1].set_ylabel("|τ̂−τ|/τ (%)")
axes[1].set_title(f"寿命拟合偏差(真值 {tau_true} ns)")
for ax2 in axes:
ax2.grid(alpha=0.3, axis="y")
print(f"\n=== M2 三方案对比(真值 τ = {tau_true} ns)===")
print(f"{'方案':<12} {'τ̂(ns)':>10} {'偏差%':>8} {'点数':>6} {'连续度(mean)':>12}")
for key, label in zip(names, labels):
d = rec[key]
err = abs(d["tau_hat"] - tau_true) / tau_true * 100 if d["tau_hat"] else float("nan")
print(f"{label:<12} {d['tau_hat']:>10.4f} {err:>8.2f} {d['n_points']:>6d} "
f"{d['continuity']['mean_jump']:>12.5f}")
print(f"完整校准系数:增益={[round(g, 3) for g in rec['calibrated']['gains']]}")
print(f"基线(相对峰值)={[round(b, 4) for b in rec['calibrated']['baselines']]}")
print(f"延时估计(ns)={[round(d, 3) for d in rec['calibrated']['delay_est_ns']]}")
run_dir = record.save_run(
runs_dir, "exp03_m2_calibration", records=[rec],
figures=[("fig1_reconstruction", fig), ("fig2_compare", fig2)],
notes=("M2 校准对比:raw / 基线+增益校准 / 完整校准。"
"校准价值体现在重建曲线连续度与 τ̂ 有界性;"
"延时常数错位不改变单指数拟合的 τ(被幅度自由度吸收)——教学点。"),
seed=seed)
print(f"\n[M2] 记录包:{run_dir}")
return run_dir
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--runs-dir", default="runs")
a = ap.parse_args()
run(seed=a.seed, runs_dir=a.runs_dir)

View File

@@ -0,0 +1,103 @@
"""M3 实验:对数线性 vs 非线性最小二乘(三档 SNR + 已知/估基线)。
运行:python -m fiber_delay_sim.experiments.exp04_m3_algorithms
"""
import argparse
import numpy as np
from ..core import fitting
from ..export import record
from ._plot import setup_style
def run(seeds=8, runs_dir="runs"):
plt = setup_style()
t = np.arange(0.0, 400.0, 10.0)
true_tau = 52.8
snrs = (30.0, 50.0, 70.0)
# 三档 SNR × 多种子:三种方法的平均相对误差
summary = []
for snr in snrs:
errs = {"nls": [], "ll_known": [], "ll_est": []}
for s in range(seeds):
rng = np.random.default_rng(s)
y = np.exp(-t / true_tau)
sigma = np.max(y) * 10 ** (-snr / 20)
yn = y + rng.normal(0, sigma, len(t))
r1 = fitting.fit_single_exp_nls(t, yn)
errs["nls"].append(abs(r1["tau"] - true_tau) / true_tau)
r2 = fitting.fit_log_linear(t, yn, b=0.0) # 已知基线(理想)
if r2["tau"]:
errs["ll_known"].append(abs(r2["tau"] - true_tau) / true_tau)
r3 = fitting.fit_log_linear(t, yn) # 默认尾段估基线
if r3["tau"]:
errs["ll_est"].append(abs(r3["tau"] - true_tau) / true_tau)
summary.append({"snr": snr,
"nls": float(np.mean(errs["nls"])),
"ll_known": float(np.mean(errs["ll_known"])) if errs["ll_known"] else None,
"ll_est": float(np.mean(errs["ll_est"])) if errs["ll_est"] else None})
print(f"\n=== M3 算法对比(真值 τ = {true_tau} ns,{seeds} 个种子平均)===")
print(f"{'SNR(dB)':>8} {'NLS':>10} {'对数(已知基线)':>14} {'对数(估基线)':>14}")
for r in summary:
print(f"{r['snr']:>8.0f} {r['nls'] * 100:>9.2f}% "
f"{(r['ll_known'] * 100 if r['ll_known'] is not None else float('nan')):>13.2f}% "
f"{(r['ll_est'] * 100 if r['ll_est'] is not None else float('nan')):>13.2f}%")
# ---------- 图 1:SNR 50 示例,两方法拟合对比(对数坐标展示尾部偏离) ----------
fig, ax = plt.subplots(figsize=(7.5, 4.4))
rng = np.random.default_rng(3)
y = np.exp(-t / true_tau)
sigma = np.max(y) * 10 ** (-50 / 20)
yn = y + rng.normal(0, sigma, len(t))
ax.semilogy(t, yn, "o", ms=4, color="#9aa5b1", label="采样数据(SNR 50 dB)")
ax.semilogy(t, np.exp(-t / true_tau), "k-", lw=1.2, label="真值")
r_nls = fitting.fit_single_exp_nls(t, yn)
r_ll = fitting.fit_log_linear(t, yn) # 估基线
ax.semilogy(t, r_nls["A"] * np.exp(-t / r_nls["tau"]) + r_nls["B"], "-", color="#2D5F8A",
label=f"NLS:τ̂ = {r_nls['tau']:.2f} ns")
if r_ll["tau"]:
ax.semilogy(t, r_ll["A"] * np.exp(-t / r_ll["tau"]), "--", color="#C25B2A",
label=f"对数线性(估基线):τ̂ = {r_ll['tau']:.2f} ns")
ax.set_xlabel("时间 (ns)")
ax.set_ylabel("归一化强度(对数坐标)")
ax.set_title("M3:对数线性 vs NLS——低幅值尾部经对数变换后噪声权重失真")
ax.legend(fontsize=9)
ax.grid(alpha=0.3, which="both")
# ---------- 图 2:平均误差 vs SNR 折线 ----------
fig2, ax2 = plt.subplots(figsize=(7, 4))
xs = [r["snr"] for r in summary]
ax2.plot(xs, [r["nls"] * 100 for r in summary], "o-", color="#2D5F8A", label="NLS")
ax2.plot(xs, [r["ll_known"] * 100 for r in summary], "s--", color="#6B2A35",
label="对数线性(已知基线)")
ax2.plot(xs, [r["ll_est"] * 100 for r in summary], "^--", color="#C25B2A",
label="对数线性(尾段估基线)")
ax2.set_xlabel("SNR (dB)")
ax2.set_ylabel("平均相对误差 |τ̂−τ|/τ (%)")
ax2.set_title("M3:三档信噪比下算法平均误差")
ax2.legend()
ax2.grid(alpha=0.3)
run_dir = record.save_run(
runs_dir, "exp04_m3_algorithms",
records=[{"meta": {"experiment": "m3_loglinear_vs_nls",
"data_origin": "software-simulated"},
"summary": summary, "true_tau": true_tau}],
figures=[("fig1_fit_example", fig), ("fig2_snr_curve", fig2)],
notes=("M3 算法对比:NLS 稳健;对数线性在已知基线下数学等价、"
"在默认尾段估基线下引入系统偏差(对数变换放大低幅值尾部噪声)。"),
)
print(f"\n[M3] 记录包:{run_dir}")
return run_dir
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--seeds", type=int, default=8)
ap.add_argument("--runs-dir", default="runs")
a = ap.parse_args()
run(seeds=a.seeds, runs_dir=a.runs_dir)

View File

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

View File

@@ -15,9 +15,20 @@ import json
import os
import subprocess
import numpy as np
from .. import ALGO_VERSION
def _json_default(o):
"""ndarray → list;标量 → 原生 float。"""
if isinstance(o, np.ndarray):
return o.tolist()
if isinstance(o, np.generic):
return o.item()
raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
def git_hash():
try:
h = subprocess.run(["git", "rev-parse", "--short", "HEAD"],
@@ -82,7 +93,7 @@ def save_run(runs_dir, name, records, figures=None, notes="", seed=None, extra_m
with open(os.path.join(run_dir, "meta.json"), "w") as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
with open(os.path.join(run_dir, "results.json"), "w") as f:
json.dump(results, f, ensure_ascii=False, indent=2, default=float)
json.dump(results, f, ensure_ascii=False, indent=2, default=_json_default)
for fname, fig in (figures or []):
fig.savefig(os.path.join(run_dir, "figures", f"{fname}.svg"))

View File

@@ -1,11 +1,14 @@
"""实验流程编排:参数 → 生成 → 采样 → 拟合 → 结果(纯数据,Pyodide 可运行)。
"""实验流程编排:参数 → 生成 → 采样 → 校准 → 拟合 → 统计(纯数据,Pyodide 可运行)。
M0:单指数信号 + 10 ns 直接采样 + 噪声 + NLS 寿命拟合。
里程碑映射:
- M0:单指数信号 + 10 ns 直接采样 + 噪声 + NLS 寿命拟合;
- M2:四通道光纤延时采样 + 通道误差注入 + 校准(名义 vs 标定)对比;
- M4:单通道直接采样 vs 四相位等效采样 的双指数 τ₂ 蒙特卡洛对比。
"""
import numpy as np
from .core import acquisition, fitting, signal
from .core import acquisition, calibration, fitting, signal, statistics
from . import ALGO_VERSION
M0_DEFAULTS = {
@@ -99,3 +102,145 @@ def run_m0_repeats(params=None, repeats=20, seed=0):
"rel_std": float(np.std(arr, ddof=1) / mean) if len(arr) > 1 and mean else None,
"bias": float((mean - tau_true) / tau_true) if tau_true else None,
}
# ---------- M2:四通道误差注入与校准 ----------
M2_DEFAULTS = {
"preset": "single", "tau": 52.8, "window_ns": 400.0, "dt_ns": 10.0,
"snr_db": 50.0, "bits": 12,
"delays_ns": [0.0, 47.5, 95.0, 142.5],
"gain_errors": [0.0, 0.10, -0.08, 0.06], # 通道失配(相对,教学上取可见幅度)
"delay_errors": [0.0, 0.5, -0.4, 0.3], # 延时误差 ns
"baselines": [0.0, 0.02, -0.015, 0.01], # 基线(相对峰值)
"calib_residual_ns": 0.05, # 标定残差 ns(对应原项目 0.01ns 级)
}
def run_m2(params=None, seed=42):
"""M2:四通道采样 + 误差注入 + 三种处理方案对比(不校准 / 基线增益校准 / 完整校准)。"""
p = dict(M2_DEFAULTS)
p.update({k: v for k, v in (params or {}).items()})
rng = np.random.default_rng(seed)
sig_params = signal.resolve_preset(p["preset"], tau=p["tau"])
t_cont = np.arange(0.0, float(p["window_ns"]) + CONT_STEP_NS / 2, CONT_STEP_NS)
y_cont = signal.generate(t_cont, sig_params)
acq = acquisition.run_multi_channel(t_cont, y_cont, {
"delays": p["delays_ns"], "gain_errors": p["gain_errors"],
"delay_errors": p["delay_errors"], "baselines": p["baselines"],
"dt_ns": p["dt_ns"], "window_ns": p["window_ns"],
"snr_db": p["snr_db"], "bits": p["bits"],
}, rng)
# 方案 raw:完全不校准(原始数据 + 名义延时)
cal_raw = calibration.calibrate_channels(
acq["channels"], p["dt_ns"], method="nominal",
do_baseline=False, do_gain=False)
# 方案 nominal:基线 + 增益校准,延时仍用名义值
cal_nominal = calibration.calibrate_channels(acq["channels"], p["dt_ns"], method="nominal")
# 方案 calibrated:完整校准(标定延时 = 真实延时 + 标定残差)
true_delays = [d + e for d, e in zip(p["delays_ns"], p["delay_errors"])]
calib_delays = [d + r for d, r in zip(true_delays,
[0.0] + [p["calib_residual_ns"]] * (len(true_delays) - 1))]
cal_calib = calibration.calibrate_channels(acq["channels"], p["dt_ns"],
delay_est_ns=calib_delays)
def _fit(cal):
if cal["n_points"] < 3:
return None
try:
return fitting.fit_single_exp_nls(cal["t_rebuilt"], cal["y_rebuilt"])["tau"]
except Exception:
return None
tau_true = float(sig_params["tau2"])
return {
"meta": {"experiment": "m2_four_channel_calibration",
"algo_version": ALGO_VERSION, "data_origin": "software-simulated",
"seed": int(seed), "params": p},
"tau_true": tau_true,
"channels": acq["channels"],
"sigma": acq["sigma"], "peak": acq["peak"],
"raw": {"t": cal_raw["t_rebuilt"], "y": cal_raw["y_rebuilt"],
"tau_hat": _fit(cal_raw), "n_points": cal_raw["n_points"],
"continuity": cal_raw["continuity"]},
"nominal": {"t": cal_nominal["t_rebuilt"], "y": cal_nominal["y_rebuilt"],
"tau_hat": _fit(cal_nominal), "n_points": cal_nominal["n_points"],
"continuity": cal_nominal["continuity"]},
"calibrated": {"t": cal_calib["t_rebuilt"], "y": cal_calib["y_rebuilt"],
"tau_hat": _fit(cal_calib), "n_points": cal_calib["n_points"],
"continuity": cal_calib["continuity"],
"baselines": cal_calib["baselines"], "gains": cal_calib["gains"],
"delay_est_ns": cal_calib["delay_used_ns"]},
}
# ---------- M4:单通道 vs 四相位等效采样(双指数 τ₂ 蒙特卡洛) ----------
M4_DEFAULTS = {
"preset": "monte_carlo", # 双指数 0.16/0.60 + 0.84/52.80(报告 5.4.4 真值)
"window_ns": 400.0, "dt_ns": 10.0,
"snr_db": 50.0, "bits": 14,
"delays_ns": [0.0, 47.5, 95.0, 142.5],
"gain_errors": [0.0] * 4, "delay_errors": [0.0] * 4, "baselines": [0.0] * 4,
}
def _fit_double_tau2(t, y):
if len(t) < 6:
return None
try:
return fitting.fit_double_exp_nls(t, y)["tau2"]
except Exception:
return None
def _gen_single(seed, p):
"""单通道 10ns 直接采样 → 双指数拟合 τ₂。"""
rng = np.random.default_rng(seed)
sig_params = signal.resolve_preset(p["preset"])
t_cont = np.arange(0.0, float(p["window_ns"]) + CONT_STEP_NS / 2, CONT_STEP_NS)
y_cont = signal.generate(t_cont, sig_params)
acq = acquisition.run_single_channel(t_cont, y_cont, {
"dt_ns": p["dt_ns"], "window_ns": p["window_ns"],
"snr_db": p["snr_db"], "bits": p["bits"],
}, rng)
return _fit_double_tau2(acq["t_samples"], acq["y_samples"])
def _gen_fiber(seed, p):
"""四相位等效采样(理想校准)→ 重建 → 双指数拟合 τ₂。"""
rng = np.random.default_rng(seed)
sig_params = signal.resolve_preset(p["preset"])
t_cont = np.arange(0.0, float(p["window_ns"]) + CONT_STEP_NS / 2, CONT_STEP_NS)
y_cont = signal.generate(t_cont, sig_params)
acq = acquisition.run_multi_channel(t_cont, y_cont, {
"delays": p["delays_ns"], "gain_errors": p["gain_errors"],
"delay_errors": p["delay_errors"], "baselines": p["baselines"],
"dt_ns": p["dt_ns"], "window_ns": p["window_ns"],
"snr_db": p["snr_db"], "bits": p["bits"],
}, rng)
cal = calibration.calibrate_channels(acq["channels"], p["dt_ns"], method="nominal",
do_baseline=False, do_gain=False)
return _fit_double_tau2(cal["t_rebuilt"], cal["y_rebuilt"])
def run_m4_compare(repeats=200, seed=0, snr_db=50.0):
"""M4 核心:单通道 vs 四相位 的 τ₂ 蒙特卡洛对比(复现 7.65%→0.60% 量级)。"""
p = dict(M4_DEFAULTS)
p["snr_db"] = snr_db
st_single = statistics.monte_carlo(
lambda s: _gen_single(s, p), repeats=repeats, seed=seed, tau_true=52.80)
st_fiber = statistics.monte_carlo(
lambda s: _gen_fiber(s, p), repeats=repeats, seed=seed, tau_true=52.80)
return {
"meta": {"experiment": "m4_monte_carlo_single_vs_fiber",
"algo_version": ALGO_VERSION, "data_origin": "software-simulated",
"repeats": int(repeats), "base_seed": int(seed),
"params": {k: v for k, v in p.items()}},
"tau_true": 52.80,
"single": st_single,
"fiber": st_fiber,
}

View File

@@ -0,0 +1,99 @@
"""M2/M3/M4 验收测试(docs/实现方案.md §11–§12)。"""
import numpy as np
import pytest
from fiber_delay_sim import pipeline
from fiber_delay_sim.core import acquisition, calibration, fitting, signal, statistics
# ---------- M2:四通道误差注入与校准 ----------
def test_multi_channel_phase_grid():
"""四通道理想延时:等效时间网格应为 0/2.5/5/7.5 ns(+10ns 周期重复)。"""
t_cont = np.arange(0.0, 400.0, 0.01)
y_cont = signal.generate(t_cont, signal.PRESETS["single"])
rng = np.random.default_rng(1)
acq = acquisition.run_multi_channel(t_cont, y_cont, {
"delays": [0.0, 47.5, 95.0, 142.5],
"dt_ns": 10.0, "window_ns": 400.0, "snr_db": None, "bits": None,
}, rng)
assert acq["n_channels"] == 4
assert acq["n_samples"] == 40
# 等效时间 = t_adc − delay(含负值,应过滤)
cal = calibration.calibrate_channels(acq["channels"], 10.0, method="nominal")
assert cal["n_points"] > 0
phases = np.unique(np.round(cal["t_rebuilt"] % 10.0, 6))
# 应覆盖 0/2.5/5/7.5 四个相位(±0.1 容差,考虑尾部裁剪)
expected = {0.0, 2.5, 5.0, 7.5}
found = {float(p) for p in phases if p < 10}
assert expected <= found or len(expected & found) >= 4
def test_m2_calibration_improves_fit():
"""M2 验收:注入误差后,完整校准比不校准的(1)重建曲线更连续、(2)τ̂ 有界。"""
rec = pipeline.run_m2({"snr_db": 60.0, "bits": 14}, seed=42)
j_raw = rec["raw"]["continuity"]["mean_jump"]
j_cal = rec["calibrated"]["continuity"]["mean_jump"]
assert j_cal < j_raw # 校准消除通道断层(连续度改善)
err = abs(rec["calibrated"]["tau_hat"] - rec["tau_true"]) / rec["tau_true"]
assert err < 0.05
assert rec["calibrated"]["tau_hat"] is not None
def test_m2_zero_error_ideal():
"""零误差 + 理想条件:不校准(raw)也应精确恢复设定寿命(真值基线天然为 0)。"""
rec = pipeline.run_m2({"gain_errors": [0.0] * 4, "delay_errors": [0.0] * 4,
"baselines": [0.0] * 4, "calib_residual_ns": 0.0,
"snr_db": None, "bits": None}, seed=3)
d_raw = abs(rec["raw"]["tau_hat"] - rec["tau_true"]) / rec["tau_true"]
assert d_raw < 1e-6
def test_m3_algorithms_on_noisy_data():
"""三档 SNR 下:NLS 有界(<5%);默认"尾段估基线"的对数线性因基线误差显著劣于 NLS。"""
t = np.arange(0.0, 400.0, 10.0)
for snr in (30.0, 50.0, 70.0):
errs_nls, errs_ll = [], []
for s in range(8):
rng = np.random.default_rng(s)
y = np.exp(-t / 52.8)
sigma = np.max(y) * 10 ** (-snr / 20)
yn = y + rng.normal(0, sigma, len(t))
r_nls = fitting.fit_single_exp_nls(t, yn)
errs_nls.append(abs(r_nls["tau"] - 52.8) / 52.8)
r_ll = fitting.fit_log_linear(t, yn) # 默认尾段估基线(学生常规操作)
if r_ll["tau"]:
errs_ll.append(abs(r_ll["tau"] - 52.8) / 52.8)
assert np.mean(errs_nls) < 0.05 # NLS 稳健
assert len(errs_ll) > 0
assert np.mean(errs_ll) > np.mean(errs_nls) # 估基线 → 对数线性系统偏差
# ---------- M4:单通道 vs 四相位蒙特卡洛 ----------
def test_m4_single_vs_fiber_relstd():
"""M4 验收:四相位等效采样 τ₂ 相对标准差应显著低于单通道(复现原项目量级)。"""
cmp = pipeline.run_m4_compare(repeats=40, seed=0, snr_db=50.0)
s, f = cmp["single"]["rel_std"], cmp["fiber"]["rel_std"]
assert s is not None and f is not None
assert f < s * 0.5 # 精度提升至少一半以上
assert f < 0.02 # 四相位 τ₂ 相对标准差应 < 2%
print(f"[M4] 单通道 rel_std={s:.3%} vs 四相位={f:.3%}")
def test_m4_failure_rate_drops():
"""失败率(|Δτ/τ|>5%)应在四相位下显著降低。"""
cmp = pipeline.run_m4_compare(repeats=40, seed=1, snr_db=40.0)
fr_s = cmp["single"]["failure_rate"]
fr_f = cmp["fiber"]["failure_rate"]
assert fr_f <= fr_s
def test_statistics_confidence_interval():
"""置信区间:已知真值应落在 95% CI 附近(教学正态近似)。"""
rng = np.random.default_rng(0)
vals = rng.normal(52.8, 0.5, 200)
ci = statistics.confidence_interval(vals)
assert abs(ci["mean"] - 52.8) < 0.15
assert ci["ci_lo"] < 52.8 < ci["ci_hi"]