diff --git a/README.md b/README.md index 455c5b7..9e53451 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,8 @@ python -m fiber_delay_sim.cli design --targets 0,2.5,5,7.5 | 里程碑 | 内容 | 状态 | |---|---|---| -| M0 最小程序 | 信号生成 + 10ns 采样 + 噪声 + NLS 寿命拟合(验收:理想无噪恢复设定寿命) | 🔄 进行中 | -| M1 光纤设计 | 长度→延时→相位 + 反向设计 + 相位图 | 🔄 进行中 | +| M0 最小程序 | 信号生成 + 10ns 采样 + 噪声 + NLS 寿命拟合(验收:理想无噪恢复设定寿命) | ✅ 完成(理想偏差 1.4e-16;加噪 20 次重复 σ=0.42%) | +| M1 光纤设计 | 长度→延时→相位 + 反向设计 + 相位图 | ✅ 完成(相位严格均匀;反向设计复现原项目方案) | | M2 误差与校准 | 四通道误差注入 + 校准 + 时间重建 | ⬜ | | M3 算法切换 | 对数线性 vs 非线性最小二乘 | ⬜ | | M4 统计分析 | 蒙特卡洛 + 参数扫描 + 置信区间 + 失败率 | ⬜ | @@ -67,8 +67,10 @@ python -m fiber_delay_sim.cli design --targets 0,2.5,5,7.5 ## 展示网站 - 地址:**https://chenxy.biboer.cn** (静态站:Pyodide 在浏览器运行同一 `core/` 算法核心 + ECharts 渲染,算法与本地/论文零重写) -- 本地预览:`python3 -m http.server -d web 8765` → 访问 http://localhost:8765 -- 首次加载需下载 Pyodide 运行时(约数十 MB),请耐心等待 +- 部署链路:`chenxy.biboer.cn`(Cloudflare DNS + mac-tunnel 隧道)→ m4 本机 `cloudflared` → `http://127.0.0.1:5050`(Homebrew nginx,TLS 由 Cloudflare 终止)→ 站点目录 `/Users/gavin/www/chenxy` +- 发布流程:`./deploy.sh local` 同步 core 到 web/py → `rsync -az web/ m4:/Users/gavin/www/chenxy/`(详见 `docs/实现方案.md` 附录 B) +- 本地预览:`python3 -m http.server -d web 8766` → 访问 http://127.0.0.1:8766 +- 首次加载需下载 Pyodide 运行时(约 40 MB),请耐心等待 ## 数据与诚信声明 diff --git a/deploy.sh b/deploy.sh index e5f3790..9d07c97 100755 --- a/deploy.sh +++ b/deploy.sh @@ -1,31 +1,31 @@ #!/usr/bin/env bash -# deploy.sh —— 构建并部署展示网站到 chenxy.biboer.cn -# 用法:./deploy.sh 构建 + 上传 + nginx 检查 -# ./deploy.sh local 仅同步 core 到 web/py(本地预览用) +# deploy.sh —— 构建并部署展示网站到 m4(chenxy.biboer.cn,cloudflared → nginx:5050) +# 用法: +# ./deploy.sh 同步 core 到 web/py + rsync 到 m4 站点目录 +# ./deploy.sh local 仅同步 core 到 web/py(本地预览用) set -euo pipefail -REMOTE_HOST="web" # ssh config 中的主机别名 -SITE_DIR="/var/www/chenxy" # 服务器站点目录 +REMOTE_HOST="m4" # ssh config 中的主机别名 +SITE_DIR="/Users/gavin/www/chenxy" # m4 上 nginx 站点目录(nginx conf: servers/chenxy.biboer.cn.conf) DOMAIN="chenxy.biboer.cn" -echo "[1/4] 同步算法核心 fiber_delay_sim -> web/py/" +echo "[1/3] 同步算法核心 fiber_delay_sim -> web/py/" rsync -a --delete --exclude '__pycache__' --exclude 'tests' \ --exclude 'experiments' --exclude 'export' --exclude 'cli.py' \ fiber_delay_sim/ web/py/fiber_delay_sim/ if [ "${1:-}" = "local" ]; then - echo "[done] 本地预览:python3 -m http.server -d web 8765 → http://localhost:8765" + echo "[done] 本地预览:python3 -m http.server -d web 8766 → http://127.0.0.1:8766" exit 0 fi -echo "[2/4] 上传 web/ -> ${REMOTE_HOST}:${SITE_DIR}/" -ssh "$REMOTE_HOST" "mkdir -p ${SITE_DIR}" -rsync -az --delete web/ "$REMOTE_HOST:${SITE_DIR}/" +echo "[2/3] 上传 web/ -> ${REMOTE_HOST}:${SITE_DIR}/" +ssh -o RemoteCommand=none -o RequestTTY=no "$REMOTE_HOST" "mkdir -p ${SITE_DIR}" +rsync -az --delete -e "ssh -o RemoteCommand=none -o RequestTTY=no" web/ "${REMOTE_HOST}:${SITE_DIR}/" -echo "[3/4] 检查 nginx 站点配置(${DOMAIN})" -ssh "$REMOTE_HOST" "test -f /etc/nginx/conf.d/${DOMAIN}.conf && echo 'conf 存在' || echo 'conf 缺失'" - -echo "[4/4] 验证站点" +echo "[3/3] 验证" sleep 1 -curl -sI "https://${DOMAIN}" | head -5 -echo "[done] 部署完成:https://${DOMAIN}" +ssh -o RemoteCommand=none -o RequestTTY=no "$REMOTE_HOST" \ + "curl -s -o /dev/null -w 'm4 localhost:5050 -> HTTP %{http_code}\\n' http://127.0.0.1:5050/" +echo "[done] 部署完成:https://${DOMAIN}(静态资源/算法文件已更新,刷新浏览器即可)" +echo "[hint] 若 nginx 配置有改动,需在 m4 上执行:sudo /opt/homebrew/bin/nginx -s reload" \ No newline at end of file diff --git a/docs/实现方案.md b/docs/实现方案.md index 70494fc..143569e 100644 --- a/docs/实现方案.md +++ b/docs/实现方案.md @@ -398,10 +398,12 @@ runs/YYYYMMDD-HHMMSS-<实验名>-/ | 项 | 说明 | |---|---| -| 域名 | `https://chenxy.biboer.cn`(HTTPS 已配置,证书有效期至 2027-01-10) | -| 服务器 | 24.233.3.126(`ssh web`),nginx 当前为 302 占位配置,首次部署时替换为静态站点 root | -| 发布方式 | `deploy.sh` 一键同步:rsync `web/` + `core/*.py` + 记录包 JSON 至站点目录,nginx reload | -| 目录 | 站点根仅放静态产物;不部署源码与无关文件 | +| 访问地址 | `https://chenxy.biboer.cn`(TLS 由 Cloudflare 隧道终止) | +| 公网链路 | `chenxy.biboer.cn`(Cloudflare DNS CNAME)→ mac-tunnel(`cloudflared`)→ `http://127.0.0.1:5050` | +| 服务器 | m4(Homebrew nginx,监听 5050 仅 HTTP;站点目录 `/Users/gavin/www/chenxy`) | +| 域名脚本 | m4 上 `./yuming.sh chenxy.biboer.cn 5050` 管理隧道与 nginx 占位配置 | +| 发布方式 | `./deploy.sh local`(同步 core 到 web/py)→ `rsync -az web/ m4:/Users/gavin/www/chenxy/` | +| 注意 | m4 nginx master 由 root/launchd 管理,改配置后需 `sudo /opt/homebrew/bin/nginx -s reload`;`py/json` 文件配置 `no-store`,发布新算法后浏览器强制刷新 | ### B.4 内容纪律(诚信红线在网站的落实) diff --git a/fiber_delay_sim/__init__.py b/fiber_delay_sim/__init__.py index e17aab6..be8aa01 100644 --- a/fiber_delay_sim/__init__.py +++ b/fiber_delay_sim/__init__.py @@ -5,5 +5,5 @@ (约束见 docs/实现方案.md §5.1)。 """ -__version__ = "0.1.0" -ALGO_VERSION = "M0+M1" +__version__ = "0.5.0" +ALGO_VERSION = "M0-M4" diff --git a/fiber_delay_sim/__pycache__/__init__.cpython-312.pyc b/fiber_delay_sim/__pycache__/__init__.cpython-312.pyc index e2f308e..494dfa8 100644 Binary files a/fiber_delay_sim/__pycache__/__init__.cpython-312.pyc and b/fiber_delay_sim/__pycache__/__init__.cpython-312.pyc differ diff --git a/fiber_delay_sim/__pycache__/cli.cpython-312.pyc b/fiber_delay_sim/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000..67c4916 Binary files /dev/null and b/fiber_delay_sim/__pycache__/cli.cpython-312.pyc differ diff --git a/fiber_delay_sim/__pycache__/pipeline.cpython-312.pyc b/fiber_delay_sim/__pycache__/pipeline.cpython-312.pyc index aaf0eee..563b683 100644 Binary files a/fiber_delay_sim/__pycache__/pipeline.cpython-312.pyc and b/fiber_delay_sim/__pycache__/pipeline.cpython-312.pyc differ diff --git a/fiber_delay_sim/cli.py b/fiber_delay_sim/cli.py index f226180..1ed20f8 100644 --- a/fiber_delay_sim/cli.py +++ b/fiber_delay_sim/cli.py @@ -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) diff --git a/fiber_delay_sim/core/__init__.py b/fiber_delay_sim/core/__init__.py index c00b203..70d0ce4 100644 --- a/fiber_delay_sim/core/__init__.py +++ b/fiber_delay_sim/core/__init__.py @@ -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"] \ No newline at end of file diff --git a/fiber_delay_sim/core/__pycache__/__init__.cpython-312.pyc b/fiber_delay_sim/core/__pycache__/__init__.cpython-312.pyc index e81cc43..1491121 100644 Binary files a/fiber_delay_sim/core/__pycache__/__init__.cpython-312.pyc and b/fiber_delay_sim/core/__pycache__/__init__.cpython-312.pyc differ diff --git a/fiber_delay_sim/core/__pycache__/acquisition.cpython-312.pyc b/fiber_delay_sim/core/__pycache__/acquisition.cpython-312.pyc index 7b8361e..1923855 100644 Binary files a/fiber_delay_sim/core/__pycache__/acquisition.cpython-312.pyc and b/fiber_delay_sim/core/__pycache__/acquisition.cpython-312.pyc differ diff --git a/fiber_delay_sim/core/__pycache__/calibration.cpython-312.pyc b/fiber_delay_sim/core/__pycache__/calibration.cpython-312.pyc new file mode 100644 index 0000000..c1e79e4 Binary files /dev/null and b/fiber_delay_sim/core/__pycache__/calibration.cpython-312.pyc differ diff --git a/fiber_delay_sim/core/__pycache__/statistics.cpython-312.pyc b/fiber_delay_sim/core/__pycache__/statistics.cpython-312.pyc new file mode 100644 index 0000000..8557f19 Binary files /dev/null and b/fiber_delay_sim/core/__pycache__/statistics.cpython-312.pyc differ diff --git a/fiber_delay_sim/core/acquisition.py b/fiber_delay_sim/core/acquisition.py index 92facec..2c848bd 100644 --- a/fiber_delay_sim/core/acquisition.py +++ b/fiber_delay_sim/core/acquisition.py @@ -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, + } diff --git a/fiber_delay_sim/core/calibration.py b/fiber_delay_sim/core/calibration.py new file mode 100644 index 0000000..1c00999 --- /dev/null +++ b/fiber_delay_sim/core/calibration.py @@ -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))), + } \ No newline at end of file diff --git a/fiber_delay_sim/core/statistics.py b/fiber_delay_sim/core/statistics.py new file mode 100644 index 0000000..5717f35 --- /dev/null +++ b/fiber_delay_sim/core/statistics.py @@ -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} \ No newline at end of file diff --git a/fiber_delay_sim/experiments/__pycache__/exp03_m2_calibration.cpython-312.pyc b/fiber_delay_sim/experiments/__pycache__/exp03_m2_calibration.cpython-312.pyc new file mode 100644 index 0000000..0eb9057 Binary files /dev/null and b/fiber_delay_sim/experiments/__pycache__/exp03_m2_calibration.cpython-312.pyc differ diff --git a/fiber_delay_sim/experiments/__pycache__/exp04_m3_algorithms.cpython-312.pyc b/fiber_delay_sim/experiments/__pycache__/exp04_m3_algorithms.cpython-312.pyc new file mode 100644 index 0000000..821768f Binary files /dev/null and b/fiber_delay_sim/experiments/__pycache__/exp04_m3_algorithms.cpython-312.pyc differ diff --git a/fiber_delay_sim/experiments/__pycache__/exp05_m4_statistics.cpython-312.pyc b/fiber_delay_sim/experiments/__pycache__/exp05_m4_statistics.cpython-312.pyc new file mode 100644 index 0000000..1f0fedb Binary files /dev/null and b/fiber_delay_sim/experiments/__pycache__/exp05_m4_statistics.cpython-312.pyc differ diff --git a/fiber_delay_sim/experiments/exp03_m2_calibration.py b/fiber_delay_sim/experiments/exp03_m2_calibration.py new file mode 100644 index 0000000..7fe2772 --- /dev/null +++ b/fiber_delay_sim/experiments/exp03_m2_calibration.py @@ -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) \ No newline at end of file diff --git a/fiber_delay_sim/experiments/exp04_m3_algorithms.py b/fiber_delay_sim/experiments/exp04_m3_algorithms.py new file mode 100644 index 0000000..1da2414 --- /dev/null +++ b/fiber_delay_sim/experiments/exp04_m3_algorithms.py @@ -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) \ No newline at end of file diff --git a/fiber_delay_sim/experiments/exp05_m4_statistics.py b/fiber_delay_sim/experiments/exp05_m4_statistics.py new file mode 100644 index 0000000..afedd9b --- /dev/null +++ b/fiber_delay_sim/experiments/exp05_m4_statistics.py @@ -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) \ No newline at end of file diff --git a/fiber_delay_sim/export/__pycache__/record.cpython-312.pyc b/fiber_delay_sim/export/__pycache__/record.cpython-312.pyc index 32fc081..2d78b7c 100644 Binary files a/fiber_delay_sim/export/__pycache__/record.cpython-312.pyc and b/fiber_delay_sim/export/__pycache__/record.cpython-312.pyc differ diff --git a/fiber_delay_sim/export/record.py b/fiber_delay_sim/export/record.py index 431869f..481094c 100644 --- a/fiber_delay_sim/export/record.py +++ b/fiber_delay_sim/export/record.py @@ -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")) diff --git a/fiber_delay_sim/pipeline.py b/fiber_delay_sim/pipeline.py index 5a23e65..130ae50 100644 --- a/fiber_delay_sim/pipeline.py +++ b/fiber_delay_sim/pipeline.py @@ -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, + } diff --git a/fiber_delay_sim/tests/__pycache__/test_m2_m4.cpython-312-pytest-9.1.1.pyc b/fiber_delay_sim/tests/__pycache__/test_m2_m4.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000..0cb2cde Binary files /dev/null and b/fiber_delay_sim/tests/__pycache__/test_m2_m4.cpython-312-pytest-9.1.1.pyc differ diff --git a/fiber_delay_sim/tests/test_m2_m4.py b/fiber_delay_sim/tests/test_m2_m4.py new file mode 100644 index 0000000..0e2124b --- /dev/null +++ b/fiber_delay_sim/tests/test_m2_m4.py @@ -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"] \ No newline at end of file diff --git a/runs/20261012-155747-exp04_m3_algorithms/README.md b/runs/20261012-155747-exp04_m3_algorithms/README.md new file mode 100644 index 0000000..a6f17fc --- /dev/null +++ b/runs/20261012-155747-exp04_m3_algorithms/README.md @@ -0,0 +1,8 @@ +# 记录包:exp04_m3_algorithms + +M3 算法对比:NLS 稳健;对数线性在已知基线下数学等价、在默认尾段估基线下引入系统偏差(对数变换放大低幅值尾部噪声)。 + +- 运行时间:2026-10-12T15:57:47 +- git:db63516,算法版本:M0+M1 +- 数据来源:**软件仿真(software-simulated)**,非装置实测 +- 复现:`pytest fiber_delay_sim/tests/` 或重跑对应 experiments 脚本 diff --git a/runs/20261012-155747-exp04_m3_algorithms/figures/fig1_fit_example.png b/runs/20261012-155747-exp04_m3_algorithms/figures/fig1_fit_example.png new file mode 100644 index 0000000..5e54cf1 Binary files /dev/null and b/runs/20261012-155747-exp04_m3_algorithms/figures/fig1_fit_example.png differ diff --git a/runs/20261012-155747-exp04_m3_algorithms/figures/fig1_fit_example.svg b/runs/20261012-155747-exp04_m3_algorithms/figures/fig1_fit_example.svg new file mode 100644 index 0000000..cfef981 --- /dev/null +++ b/runs/20261012-155747-exp04_m3_algorithms/figures/fig1_fit_example.svg @@ -0,0 +1,3296 @@ + + + + + + + + 2026-10-12T15:57:48.018687 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155747-exp04_m3_algorithms/figures/fig2_snr_curve.png b/runs/20261012-155747-exp04_m3_algorithms/figures/fig2_snr_curve.png new file mode 100644 index 0000000..c1a1407 Binary files /dev/null and b/runs/20261012-155747-exp04_m3_algorithms/figures/fig2_snr_curve.png differ diff --git a/runs/20261012-155747-exp04_m3_algorithms/figures/fig2_snr_curve.svg b/runs/20261012-155747-exp04_m3_algorithms/figures/fig2_snr_curve.svg new file mode 100644 index 0000000..9f2db4d --- /dev/null +++ b/runs/20261012-155747-exp04_m3_algorithms/figures/fig2_snr_curve.svg @@ -0,0 +1,2217 @@ + + + + + + + + 2026-10-12T15:57:48.222571 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155747-exp04_m3_algorithms/meta.json b/runs/20261012-155747-exp04_m3_algorithms/meta.json new file mode 100644 index 0000000..76d0d95 --- /dev/null +++ b/runs/20261012-155747-exp04_m3_algorithms/meta.json @@ -0,0 +1,9 @@ +{ + "created": "2026-10-12T15:57:47", + "git_hash": "db63516", + "algo_version": "M0+M1", + "data_origin": "software-simulated", + "experiment": "exp04_m3_algorithms", + "notes": "M3 算法对比:NLS 稳健;对数线性在已知基线下数学等价、在默认尾段估基线下引入系统偏差(对数变换放大低幅值尾部噪声)。", + "params": null +} \ No newline at end of file diff --git a/runs/20261012-155747-exp04_m3_algorithms/results.json b/runs/20261012-155747-exp04_m3_algorithms/results.json new file mode 100644 index 0000000..ec2649b --- /dev/null +++ b/runs/20261012-155747-exp04_m3_algorithms/results.json @@ -0,0 +1,3 @@ +[ + {} +] \ No newline at end of file diff --git a/runs/20261012-155750-exp05_m4_statistics/README.md b/runs/20261012-155750-exp05_m4_statistics/README.md new file mode 100644 index 0000000..408f265 --- /dev/null +++ b/runs/20261012-155750-exp05_m4_statistics/README.md @@ -0,0 +1,8 @@ +# 记录包:exp05_m4_statistics + +M4 统计:主场景(SNR 50 dB)单通道 vs 四相位 τ₂ 蒙特卡洛;欠采样场景(SNR 40 dB);窗口扫描 rel_std。 + +- 运行时间:2026-10-12T15:57:50 +- git:db63516,算法版本:M0+M1 +- 数据来源:**软件仿真(software-simulated)**,非装置实测 +- 复现:`pytest fiber_delay_sim/tests/` 或重跑对应 experiments 脚本 diff --git a/runs/20261012-155750-exp05_m4_statistics/figures/fig1_hist.png b/runs/20261012-155750-exp05_m4_statistics/figures/fig1_hist.png new file mode 100644 index 0000000..eaa2916 Binary files /dev/null and b/runs/20261012-155750-exp05_m4_statistics/figures/fig1_hist.png differ diff --git a/runs/20261012-155750-exp05_m4_statistics/figures/fig1_hist.svg b/runs/20261012-155750-exp05_m4_statistics/figures/fig1_hist.svg new file mode 100644 index 0000000..0b0a5a8 --- /dev/null +++ b/runs/20261012-155750-exp05_m4_statistics/figures/fig1_hist.svg @@ -0,0 +1,3394 @@ + + + + + + + + 2026-10-12T15:57:50.763322 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155750-exp05_m4_statistics/figures/fig2_undersampled.png b/runs/20261012-155750-exp05_m4_statistics/figures/fig2_undersampled.png new file mode 100644 index 0000000..6225f79 Binary files /dev/null and b/runs/20261012-155750-exp05_m4_statistics/figures/fig2_undersampled.png differ diff --git a/runs/20261012-155750-exp05_m4_statistics/figures/fig2_undersampled.svg b/runs/20261012-155750-exp05_m4_statistics/figures/fig2_undersampled.svg new file mode 100644 index 0000000..b8d6416 --- /dev/null +++ b/runs/20261012-155750-exp05_m4_statistics/figures/fig2_undersampled.svg @@ -0,0 +1,2961 @@ + + + + + + + + 2026-10-12T15:57:50.882479 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155750-exp05_m4_statistics/figures/fig3_window_sweep.png b/runs/20261012-155750-exp05_m4_statistics/figures/fig3_window_sweep.png new file mode 100644 index 0000000..f2aefd5 Binary files /dev/null and b/runs/20261012-155750-exp05_m4_statistics/figures/fig3_window_sweep.png differ diff --git a/runs/20261012-155750-exp05_m4_statistics/figures/fig3_window_sweep.svg b/runs/20261012-155750-exp05_m4_statistics/figures/fig3_window_sweep.svg new file mode 100644 index 0000000..a664b18 --- /dev/null +++ b/runs/20261012-155750-exp05_m4_statistics/figures/fig3_window_sweep.svg @@ -0,0 +1,2709 @@ + + + + + + + + 2026-10-12T15:57:50.994520 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155750-exp05_m4_statistics/meta.json b/runs/20261012-155750-exp05_m4_statistics/meta.json new file mode 100644 index 0000000..74a169f --- /dev/null +++ b/runs/20261012-155750-exp05_m4_statistics/meta.json @@ -0,0 +1,39 @@ +{ + "created": "2026-10-12T15:57:50", + "git_hash": "db63516", + "algo_version": "M0+M1", + "data_origin": "software-simulated", + "experiment": "exp05_m4_statistics", + "notes": "M4 统计:主场景(SNR 50 dB)单通道 vs 四相位 τ₂ 蒙特卡洛;欠采样场景(SNR 40 dB);窗口扫描 rel_std。", + "params": { + "preset": "monte_carlo", + "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, + 0.0, + 0.0, + 0.0 + ], + "delay_errors": [ + 0.0, + 0.0, + 0.0, + 0.0 + ], + "baselines": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } +} \ No newline at end of file diff --git a/runs/20261012-155750-exp05_m4_statistics/results.json b/runs/20261012-155750-exp05_m4_statistics/results.json new file mode 100644 index 0000000..e20d108 --- /dev/null +++ b/runs/20261012-155750-exp05_m4_statistics/results.json @@ -0,0 +1,8 @@ +[ + { + "tau_true": 52.8 + }, + { + "tau_true": 52.8 + } +] \ No newline at end of file diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/README.md b/runs/20261012-155811-exp03_m2_calibration-seed42/README.md new file mode 100644 index 0000000..091ebff --- /dev/null +++ b/runs/20261012-155811-exp03_m2_calibration-seed42/README.md @@ -0,0 +1,8 @@ +# 记录包:exp03_m2_calibration + +M2 校准对比:raw / 基线+增益校准 / 完整校准。校准价值体现在重建曲线连续度与 τ̂ 有界性;延时常数错位不改变单指数拟合的 τ(被幅度自由度吸收)——教学点。 + +- 运行时间:2026-10-12T15:58:11 +- git:db63516,算法版本:M0+M1 +- 数据来源:**软件仿真(software-simulated)**,非装置实测 +- 复现:`pytest fiber_delay_sim/tests/` 或重跑对应 experiments 脚本 diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig1_reconstruction.png b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig1_reconstruction.png new file mode 100644 index 0000000..587187c Binary files /dev/null and b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig1_reconstruction.png differ diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig1_reconstruction.svg b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig1_reconstruction.svg new file mode 100644 index 0000000..9020d08 --- /dev/null +++ b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig1_reconstruction.svg @@ -0,0 +1,3218 @@ + + + + + + + + 2026-10-12T15:58:11.587511 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig2_compare.png b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig2_compare.png new file mode 100644 index 0000000..c83fe24 Binary files /dev/null and b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig2_compare.png differ diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig2_compare.svg b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig2_compare.svg new file mode 100644 index 0000000..43d6d21 --- /dev/null +++ b/runs/20261012-155811-exp03_m2_calibration-seed42/figures/fig2_compare.svg @@ -0,0 +1,2893 @@ + + + + + + + + 2026-10-12T15:58:11.696061 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/meta.json b/runs/20261012-155811-exp03_m2_calibration-seed42/meta.json new file mode 100644 index 0000000..84950cc --- /dev/null +++ b/runs/20261012-155811-exp03_m2_calibration-seed42/meta.json @@ -0,0 +1,42 @@ +{ + "created": "2026-10-12T15:58:11", + "git_hash": "db63516", + "algo_version": "M0+M1", + "data_origin": "software-simulated", + "experiment": "exp03_m2_calibration", + "notes": "M2 校准对比:raw / 基线+增益校准 / 完整校准。校准价值体现在重建曲线连续度与 τ̂ 有界性;延时常数错位不改变单指数拟合的 τ(被幅度自由度吸收)——教学点。", + "seed": 42, + "params": { + "preset": "single", + "tau": 52.8, + "window_ns": 400.0, + "dt_ns": 10.0, + "snr_db": 60.0, + "bits": 14, + "delays_ns": [ + 0.0, + 47.5, + 95.0, + 142.5 + ], + "gain_errors": [ + 0.0, + 0.1, + -0.08, + 0.06 + ], + "delay_errors": [ + 0.0, + 0.5, + -0.4, + 0.3 + ], + "baselines": [ + 0.0, + 0.02, + -0.015, + 0.01 + ], + "calib_residual_ns": 0.05 + } +} \ No newline at end of file diff --git a/runs/20261012-155811-exp03_m2_calibration-seed42/results.json b/runs/20261012-155811-exp03_m2_calibration-seed42/results.json new file mode 100644 index 0000000..123fb92 --- /dev/null +++ b/runs/20261012-155811-exp03_m2_calibration-seed42/results.json @@ -0,0 +1,708 @@ +[ + { + "tau_true": 52.8, + "channels": [ + { + "index": 0, + "delay_ns": 0.0, + "delay_eff_ns": 0.0, + "gain": 1.0, + "baseline": 0.0, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "y_clean": [ + 1.0, + 0.8274604732029096, + 0.684690834713183, + 0.5665546020894655, + 0.4688015391402353, + 0.3879147434152314, + 0.32098411714875263, + 0.265601669466525, + 0.2197748831002536, + 0.18185502876824997, + 0.15047784815890483, + 0.12451447144412296, + 0.10303080346176416, + 0.08525391738694733, + 0.0705442468234052, + 0.05837257585823771, + 0.04830099924173013, + 0.03996716768873539, + 0.03307125148830102, + 0.02736515340592199, + 0.02264358278653442, + 0.018736669727555028, + 0.015503853599009314, + 0.012828826035504878, + 0.010615346461976673, + 0.00878377960664005, + 0.007268230429820442, + 0.006014173390807009, + 0.0049764907598815146, + 0.004117849399061465, + 0.0034073576123257164, + 0.002819453742266576, + 0.002332986527749615, + 0.0019304541362277093, + 0.0015973744930594942, + 0.0013217642539092669, + 0.0010937076750024526, + 0.0009049998703031834, + 0.0007488516209296439, + 0.0006196451166132089 + ], + "y_samples": [ + 1.0003051944088384, + 0.8264664591344686, + 0.685466642251114, + 0.5675395226759445, + 0.46682536775926264, + 0.38662027711652325, + 0.32106451809802844, + 0.2652749801623634, + 0.21973997436366965, + 0.18104132332295672, + 0.15137642678386132, + 0.1252517853872917, + 0.10315571018738937, + 0.0864310565830434, + 0.07104925837758652, + 0.057498626625160226, + 0.04870902765061344, + 0.03906488433131905, + 0.033937618262833424, + 0.027345419031923335, + 0.022462308490508454, + 0.01806750900323506, + 0.016724653604345968, + 0.012696087407678691, + 0.010132454373435879, + 0.00842336568394067, + 0.00781297686626381, + 0.006348043703839346, + 0.005371421595556369, + 0.004516877250808765, + 0.005493499359091741, + 0.0024415552707074406, + 0.0018311664530305805, + 0.0010986998718183483, + 0.0021973997436366965, + 0.0024415552707074406, + 0.0009766221082829762, + 0.00012207776353537203, + -0.00012207776353537203, + 0.0012207776353537203 + ] + }, + { + "index": 1, + "delay_ns": 47.5, + "delay_eff_ns": 48.0, + "gain": 1.1, + "baseline": 0.02, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + -48.0, + -38.0, + -28.0, + -18.0, + -8.0, + 2.0, + 12.0, + 22.0, + 32.0, + 42.0, + 52.0, + 62.0, + 72.0, + 82.0, + 92.0, + 102.0, + 112.0, + 122.0, + 132.0, + 142.0, + 152.0, + 162.0, + 172.0, + 182.0, + 192.0, + 202.0, + 212.0, + 222.0, + 232.0, + 242.0, + 252.0, + 262.0, + 272.0, + 282.0, + 292.0, + 302.0, + 312.0, + 322.0, + 332.0, + 342.0 + ], + "y_clean": [ + 0.02, + 0.02, + 0.02, + 0.02, + 0.02, + 1.0791126044855845, + 0.8963738168828078, + 0.7451646932204882, + 0.6200451202022679, + 0.5165136191056653, + 0.4308453942168631, + 0.35995832431192143, + 0.30130207590441066, + 0.25276634884082444, + 0.21260495315754213, + 0.17937298568096405, + 0.15187484614733104, + 0.12912122259663145, + 0.1102934984862887, + 0.09471430098461064, + 0.08182313084775052, + 0.07115619710616504, + 0.06232973106472864, + 0.055026179297372246, + 0.0489827788958936, + 0.04398210393993142, + 0.03984424307453702, + 0.036420326764809954, + 0.03358717135495605, + 0.03124284723886095, + 0.029303011696415908, + 0.02769787446052851, + 0.026369686843765516, + 0.02527066408989656, + 0.02436126620191939, + 0.023608775395204076, + 0.022986118996198582, + 0.022470895437634676, + 0.0220445683080601, + 0.02169179945968308 + ], + "y_samples": [ + 0.020753219801013245, + 0.0205090642739425, + 0.01928828663858878, + 0.020264908746871757, + 0.020142830983336385, + 1.079289507416224, + 0.8972715619849845, + 0.7454068241469816, + 0.6207654275773667, + 0.5166330952816944, + 0.431178660806934, + 0.360617713483489, + 0.2998229872428737, + 0.25245681499114936, + 0.2121711530244766, + 0.17872184581578465, + 0.15162058231093206, + 0.13062320698284807, + 0.10938167612769334, + 0.09570896661173167, + 0.08008301287920405, + 0.07080510285051578, + 0.06250381493011048, + 0.055667460172129646, + 0.049685649758896416, + 0.044802539217481535, + 0.03955319538546054, + 0.03601294024293475, + 0.03442592931697491, + 0.031007751937984496, + 0.028077885613135567, + 0.026612952450711103, + 0.025392174815357382, + 0.0257584081059635, + 0.024537630470609778, + 0.024293474943539034, + 0.022584386254043826, + 0.022584386254043826, + 0.022706464017579198, + 0.021363608618690105 + ] + }, + { + "index": 2, + "delay_ns": 95.0, + "delay_eff_ns": 94.6, + "gain": 0.92, + "baseline": -0.015, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + -94.6, + -84.6, + -74.6, + -64.6, + -54.599999999999994, + -44.599999999999994, + -34.599999999999994, + -24.599999999999994, + -14.599999999999994, + -4.599999999999994, + 5.400000000000006, + 15.400000000000006, + 25.400000000000006, + 35.400000000000006, + 45.400000000000006, + 55.400000000000006, + 65.4, + 75.4, + 85.4, + 95.4, + 105.4, + 115.4, + 125.4, + 135.4, + 145.4, + 155.4, + 165.4, + 175.4, + 185.4, + 195.4, + 205.4, + 215.4, + 225.4, + 235.4, + 245.4, + 255.4, + 265.4, + 275.4, + 285.4, + 295.4 + ], + "y_clean": [ + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + 0.8155606401057288, + 0.6722561002855979, + 0.5536772579539071, + 0.45555795296627305, + 0.3743681064308647, + 0.3071867175974042, + 0.2515967738028403, + 0.20559829260526724, + 0.16753636758690832, + 0.1360416291002034, + 0.10998097788859268, + 0.08841681910505726, + 0.07057333007381038, + 0.05580854819642393, + 0.04359127479742398, + 0.03348196396943815, + 0.025116908847957704, + 0.01819515637876907, + 0.012467679805220833, + 0.0077284193294140345, + 0.003806868613471088, + 0.0005619404023677367, + -0.0021231094307013164, + -0.0043448820361460284, + -0.006183311047596571, + -0.007704538387361393, + -0.008963293881772392, + -0.010004864298824483, + -0.01086672264899256, + -0.011579876367256514 + ], + "y_samples": [ + -0.014527253860709272, + -0.01562595373252762, + -0.015381798205456876, + -0.015381798205456876, + -0.01623634255020448, + -0.014527253860709272, + -0.015503875968992248, + -0.01501556491485076, + -0.014527253860709272, + -0.014527253860709272, + 0.8162119269974975, + 0.6721601660257583, + 0.553256424342306, + 0.4554721357504731, + 0.3727034120734908, + 0.30568271989257156, + 0.25025941524751266, + 0.20460233168528352, + 0.1679790026246719, + 0.13514008423365684, + 0.10962583165476408, + 0.08972715619849844, + 0.07019471403283892, + 0.05652200451687725, + 0.04260513947384484, + 0.033327229445156564, + 0.024171397180003662, + 0.017823353476164316, + 0.013306476225355551, + 0.0059818104132332295, + 0.004272721723738021, + 0.0008545443447476042, + -0.0026857107977781847, + -0.005737654886162485, + -0.0061038881767686015, + -0.008179210156869926, + -0.008789598974546786, + -0.010010376609900506, + -0.009277910028688274, + -0.011841543062931087 + ] + }, + { + "index": 3, + "delay_ns": 142.5, + "delay_eff_ns": 142.8, + "gain": 1.06, + "baseline": 0.01, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + -142.8, + -132.8, + -122.80000000000001, + -112.80000000000001, + -102.80000000000001, + -92.80000000000001, + -82.80000000000001, + -72.80000000000001, + -62.80000000000001, + -52.80000000000001, + -42.80000000000001, + -32.80000000000001, + -22.80000000000001, + -12.800000000000011, + -2.8000000000000114, + 7.199999999999989, + 17.19999999999999, + 27.19999999999999, + 37.19999999999999, + 47.19999999999999, + 57.19999999999999, + 67.19999999999999, + 77.19999999999999, + 87.19999999999999, + 97.19999999999999, + 107.19999999999999, + 117.19999999999999, + 127.19999999999999, + 137.2, + 147.2, + 157.2, + 167.2, + 177.2, + 187.2, + 197.2, + 207.2, + 217.2, + 227.2, + 237.2, + 247.2 + ], + "y_clean": [ + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.9348768104415895, + 0.7752990032223953, + 0.6432546753481182, + 0.5339932133215087, + 0.4435836722501288, + 0.3687733506131468, + 0.3068707664709478, + 0.25564882490416097, + 0.21326469289693573, + 0.17819349896994255, + 0.14917347224732175, + 0.12516054720306086, + 0.10529080088295072, + 0.08884937119049062, + 0.07524473799703522, + 0.06398744177702662, + 0.054672474119832996, + 0.04696470657434175, + 0.04058683359381152, + 0.03530939579931393, + 0.030942524624580033, + 0.02732911133591858, + 0.024339154666205093, + 0.021865083705427772, + 0.0198178877774854 + ], + "y_samples": [ + 0.00903375450161753, + 0.010132454373435879, + 0.01025453213697125, + 0.011353232008789599, + 0.01086492095464811, + 0.010376609900506623, + 0.01147530977232497, + 0.008789598974546786, + 0.009399987792223646, + 0.00903375450161753, + 0.00964414331929439, + 0.008667521211011414, + 0.010620765427577367, + 0.009766221082829762, + 0.008545443447476042, + 0.933894891045596, + 0.7755600317402185, + 0.6440822804126228, + 0.5360434596838186, + 0.4464383812488555, + 0.369163156930965, + 0.3059268754196423, + 0.2535555148629677, + 0.21351400842336568, + 0.17737899041689556, + 0.1488127937496185, + 0.12451931880607947, + 0.10510895440395532, + 0.08997131172556919, + 0.07544405786485991, + 0.06384667032899957, + 0.05359213819202832, + 0.04529085027162302, + 0.040041506439602026, + 0.03528047366172252, + 0.032716840627479704, + 0.027467496795458707, + 0.02527009705182201, + 0.021363608618690105, + 0.01867789782091192 + ] + } + ], + "sigma": 0.001 + } +] \ No newline at end of file diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/README.md b/runs/20261012-155844-exp03_m2_calibration-seed42/README.md new file mode 100644 index 0000000..598cae3 --- /dev/null +++ b/runs/20261012-155844-exp03_m2_calibration-seed42/README.md @@ -0,0 +1,8 @@ +# 记录包:exp03_m2_calibration + +M2 校准对比:raw / 基线+增益校准 / 完整校准。校准价值体现在重建曲线连续度与 τ̂ 有界性;延时常数错位不改变单指数拟合的 τ(被幅度自由度吸收)——教学点。 + +- 运行时间:2026-10-12T15:58:44 +- git:db63516,算法版本:M0-M4 +- 数据来源:**软件仿真(software-simulated)**,非装置实测 +- 复现:`pytest fiber_delay_sim/tests/` 或重跑对应 experiments 脚本 diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig1_reconstruction.png b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig1_reconstruction.png new file mode 100644 index 0000000..587187c Binary files /dev/null and b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig1_reconstruction.png differ diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig1_reconstruction.svg b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig1_reconstruction.svg new file mode 100644 index 0000000..c36f620 --- /dev/null +++ b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig1_reconstruction.svg @@ -0,0 +1,3218 @@ + + + + + + + + 2026-10-12T15:58:44.630215 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig2_compare.png b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig2_compare.png new file mode 100644 index 0000000..c83fe24 Binary files /dev/null and b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig2_compare.png differ diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig2_compare.svg b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig2_compare.svg new file mode 100644 index 0000000..d79304a --- /dev/null +++ b/runs/20261012-155844-exp03_m2_calibration-seed42/figures/fig2_compare.svg @@ -0,0 +1,2893 @@ + + + + + + + + 2026-10-12T15:58:44.739600 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/meta.json b/runs/20261012-155844-exp03_m2_calibration-seed42/meta.json new file mode 100644 index 0000000..10d52cb --- /dev/null +++ b/runs/20261012-155844-exp03_m2_calibration-seed42/meta.json @@ -0,0 +1,42 @@ +{ + "created": "2026-10-12T15:58:44", + "git_hash": "db63516", + "algo_version": "M0-M4", + "data_origin": "software-simulated", + "experiment": "exp03_m2_calibration", + "notes": "M2 校准对比:raw / 基线+增益校准 / 完整校准。校准价值体现在重建曲线连续度与 τ̂ 有界性;延时常数错位不改变单指数拟合的 τ(被幅度自由度吸收)——教学点。", + "seed": 42, + "params": { + "preset": "single", + "tau": 52.8, + "window_ns": 400.0, + "dt_ns": 10.0, + "snr_db": 60.0, + "bits": 14, + "delays_ns": [ + 0.0, + 47.5, + 95.0, + 142.5 + ], + "gain_errors": [ + 0.0, + 0.1, + -0.08, + 0.06 + ], + "delay_errors": [ + 0.0, + 0.5, + -0.4, + 0.3 + ], + "baselines": [ + 0.0, + 0.02, + -0.015, + 0.01 + ], + "calib_residual_ns": 0.05 + } +} \ No newline at end of file diff --git a/runs/20261012-155844-exp03_m2_calibration-seed42/results.json b/runs/20261012-155844-exp03_m2_calibration-seed42/results.json new file mode 100644 index 0000000..123fb92 --- /dev/null +++ b/runs/20261012-155844-exp03_m2_calibration-seed42/results.json @@ -0,0 +1,708 @@ +[ + { + "tau_true": 52.8, + "channels": [ + { + "index": 0, + "delay_ns": 0.0, + "delay_eff_ns": 0.0, + "gain": 1.0, + "baseline": 0.0, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "y_clean": [ + 1.0, + 0.8274604732029096, + 0.684690834713183, + 0.5665546020894655, + 0.4688015391402353, + 0.3879147434152314, + 0.32098411714875263, + 0.265601669466525, + 0.2197748831002536, + 0.18185502876824997, + 0.15047784815890483, + 0.12451447144412296, + 0.10303080346176416, + 0.08525391738694733, + 0.0705442468234052, + 0.05837257585823771, + 0.04830099924173013, + 0.03996716768873539, + 0.03307125148830102, + 0.02736515340592199, + 0.02264358278653442, + 0.018736669727555028, + 0.015503853599009314, + 0.012828826035504878, + 0.010615346461976673, + 0.00878377960664005, + 0.007268230429820442, + 0.006014173390807009, + 0.0049764907598815146, + 0.004117849399061465, + 0.0034073576123257164, + 0.002819453742266576, + 0.002332986527749615, + 0.0019304541362277093, + 0.0015973744930594942, + 0.0013217642539092669, + 0.0010937076750024526, + 0.0009049998703031834, + 0.0007488516209296439, + 0.0006196451166132089 + ], + "y_samples": [ + 1.0003051944088384, + 0.8264664591344686, + 0.685466642251114, + 0.5675395226759445, + 0.46682536775926264, + 0.38662027711652325, + 0.32106451809802844, + 0.2652749801623634, + 0.21973997436366965, + 0.18104132332295672, + 0.15137642678386132, + 0.1252517853872917, + 0.10315571018738937, + 0.0864310565830434, + 0.07104925837758652, + 0.057498626625160226, + 0.04870902765061344, + 0.03906488433131905, + 0.033937618262833424, + 0.027345419031923335, + 0.022462308490508454, + 0.01806750900323506, + 0.016724653604345968, + 0.012696087407678691, + 0.010132454373435879, + 0.00842336568394067, + 0.00781297686626381, + 0.006348043703839346, + 0.005371421595556369, + 0.004516877250808765, + 0.005493499359091741, + 0.0024415552707074406, + 0.0018311664530305805, + 0.0010986998718183483, + 0.0021973997436366965, + 0.0024415552707074406, + 0.0009766221082829762, + 0.00012207776353537203, + -0.00012207776353537203, + 0.0012207776353537203 + ] + }, + { + "index": 1, + "delay_ns": 47.5, + "delay_eff_ns": 48.0, + "gain": 1.1, + "baseline": 0.02, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + -48.0, + -38.0, + -28.0, + -18.0, + -8.0, + 2.0, + 12.0, + 22.0, + 32.0, + 42.0, + 52.0, + 62.0, + 72.0, + 82.0, + 92.0, + 102.0, + 112.0, + 122.0, + 132.0, + 142.0, + 152.0, + 162.0, + 172.0, + 182.0, + 192.0, + 202.0, + 212.0, + 222.0, + 232.0, + 242.0, + 252.0, + 262.0, + 272.0, + 282.0, + 292.0, + 302.0, + 312.0, + 322.0, + 332.0, + 342.0 + ], + "y_clean": [ + 0.02, + 0.02, + 0.02, + 0.02, + 0.02, + 1.0791126044855845, + 0.8963738168828078, + 0.7451646932204882, + 0.6200451202022679, + 0.5165136191056653, + 0.4308453942168631, + 0.35995832431192143, + 0.30130207590441066, + 0.25276634884082444, + 0.21260495315754213, + 0.17937298568096405, + 0.15187484614733104, + 0.12912122259663145, + 0.1102934984862887, + 0.09471430098461064, + 0.08182313084775052, + 0.07115619710616504, + 0.06232973106472864, + 0.055026179297372246, + 0.0489827788958936, + 0.04398210393993142, + 0.03984424307453702, + 0.036420326764809954, + 0.03358717135495605, + 0.03124284723886095, + 0.029303011696415908, + 0.02769787446052851, + 0.026369686843765516, + 0.02527066408989656, + 0.02436126620191939, + 0.023608775395204076, + 0.022986118996198582, + 0.022470895437634676, + 0.0220445683080601, + 0.02169179945968308 + ], + "y_samples": [ + 0.020753219801013245, + 0.0205090642739425, + 0.01928828663858878, + 0.020264908746871757, + 0.020142830983336385, + 1.079289507416224, + 0.8972715619849845, + 0.7454068241469816, + 0.6207654275773667, + 0.5166330952816944, + 0.431178660806934, + 0.360617713483489, + 0.2998229872428737, + 0.25245681499114936, + 0.2121711530244766, + 0.17872184581578465, + 0.15162058231093206, + 0.13062320698284807, + 0.10938167612769334, + 0.09570896661173167, + 0.08008301287920405, + 0.07080510285051578, + 0.06250381493011048, + 0.055667460172129646, + 0.049685649758896416, + 0.044802539217481535, + 0.03955319538546054, + 0.03601294024293475, + 0.03442592931697491, + 0.031007751937984496, + 0.028077885613135567, + 0.026612952450711103, + 0.025392174815357382, + 0.0257584081059635, + 0.024537630470609778, + 0.024293474943539034, + 0.022584386254043826, + 0.022584386254043826, + 0.022706464017579198, + 0.021363608618690105 + ] + }, + { + "index": 2, + "delay_ns": 95.0, + "delay_eff_ns": 94.6, + "gain": 0.92, + "baseline": -0.015, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + -94.6, + -84.6, + -74.6, + -64.6, + -54.599999999999994, + -44.599999999999994, + -34.599999999999994, + -24.599999999999994, + -14.599999999999994, + -4.599999999999994, + 5.400000000000006, + 15.400000000000006, + 25.400000000000006, + 35.400000000000006, + 45.400000000000006, + 55.400000000000006, + 65.4, + 75.4, + 85.4, + 95.4, + 105.4, + 115.4, + 125.4, + 135.4, + 145.4, + 155.4, + 165.4, + 175.4, + 185.4, + 195.4, + 205.4, + 215.4, + 225.4, + 235.4, + 245.4, + 255.4, + 265.4, + 275.4, + 285.4, + 295.4 + ], + "y_clean": [ + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + -0.015, + 0.8155606401057288, + 0.6722561002855979, + 0.5536772579539071, + 0.45555795296627305, + 0.3743681064308647, + 0.3071867175974042, + 0.2515967738028403, + 0.20559829260526724, + 0.16753636758690832, + 0.1360416291002034, + 0.10998097788859268, + 0.08841681910505726, + 0.07057333007381038, + 0.05580854819642393, + 0.04359127479742398, + 0.03348196396943815, + 0.025116908847957704, + 0.01819515637876907, + 0.012467679805220833, + 0.0077284193294140345, + 0.003806868613471088, + 0.0005619404023677367, + -0.0021231094307013164, + -0.0043448820361460284, + -0.006183311047596571, + -0.007704538387361393, + -0.008963293881772392, + -0.010004864298824483, + -0.01086672264899256, + -0.011579876367256514 + ], + "y_samples": [ + -0.014527253860709272, + -0.01562595373252762, + -0.015381798205456876, + -0.015381798205456876, + -0.01623634255020448, + -0.014527253860709272, + -0.015503875968992248, + -0.01501556491485076, + -0.014527253860709272, + -0.014527253860709272, + 0.8162119269974975, + 0.6721601660257583, + 0.553256424342306, + 0.4554721357504731, + 0.3727034120734908, + 0.30568271989257156, + 0.25025941524751266, + 0.20460233168528352, + 0.1679790026246719, + 0.13514008423365684, + 0.10962583165476408, + 0.08972715619849844, + 0.07019471403283892, + 0.05652200451687725, + 0.04260513947384484, + 0.033327229445156564, + 0.024171397180003662, + 0.017823353476164316, + 0.013306476225355551, + 0.0059818104132332295, + 0.004272721723738021, + 0.0008545443447476042, + -0.0026857107977781847, + -0.005737654886162485, + -0.0061038881767686015, + -0.008179210156869926, + -0.008789598974546786, + -0.010010376609900506, + -0.009277910028688274, + -0.011841543062931087 + ] + }, + { + "index": 3, + "delay_ns": 142.5, + "delay_eff_ns": 142.8, + "gain": 1.06, + "baseline": 0.01, + "t_adc": [ + 0.0, + 10.0, + 20.0, + 30.0, + 40.0, + 50.0, + 60.0, + 70.0, + 80.0, + 90.0, + 100.0, + 110.0, + 120.0, + 130.0, + 140.0, + 150.0, + 160.0, + 170.0, + 180.0, + 190.0, + 200.0, + 210.0, + 220.0, + 230.0, + 240.0, + 250.0, + 260.0, + 270.0, + 280.0, + 290.0, + 300.0, + 310.0, + 320.0, + 330.0, + 340.0, + 350.0, + 360.0, + 370.0, + 380.0, + 390.0 + ], + "s_equiv": [ + -142.8, + -132.8, + -122.80000000000001, + -112.80000000000001, + -102.80000000000001, + -92.80000000000001, + -82.80000000000001, + -72.80000000000001, + -62.80000000000001, + -52.80000000000001, + -42.80000000000001, + -32.80000000000001, + -22.80000000000001, + -12.800000000000011, + -2.8000000000000114, + 7.199999999999989, + 17.19999999999999, + 27.19999999999999, + 37.19999999999999, + 47.19999999999999, + 57.19999999999999, + 67.19999999999999, + 77.19999999999999, + 87.19999999999999, + 97.19999999999999, + 107.19999999999999, + 117.19999999999999, + 127.19999999999999, + 137.2, + 147.2, + 157.2, + 167.2, + 177.2, + 187.2, + 197.2, + 207.2, + 217.2, + 227.2, + 237.2, + 247.2 + ], + "y_clean": [ + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.01, + 0.9348768104415895, + 0.7752990032223953, + 0.6432546753481182, + 0.5339932133215087, + 0.4435836722501288, + 0.3687733506131468, + 0.3068707664709478, + 0.25564882490416097, + 0.21326469289693573, + 0.17819349896994255, + 0.14917347224732175, + 0.12516054720306086, + 0.10529080088295072, + 0.08884937119049062, + 0.07524473799703522, + 0.06398744177702662, + 0.054672474119832996, + 0.04696470657434175, + 0.04058683359381152, + 0.03530939579931393, + 0.030942524624580033, + 0.02732911133591858, + 0.024339154666205093, + 0.021865083705427772, + 0.0198178877774854 + ], + "y_samples": [ + 0.00903375450161753, + 0.010132454373435879, + 0.01025453213697125, + 0.011353232008789599, + 0.01086492095464811, + 0.010376609900506623, + 0.01147530977232497, + 0.008789598974546786, + 0.009399987792223646, + 0.00903375450161753, + 0.00964414331929439, + 0.008667521211011414, + 0.010620765427577367, + 0.009766221082829762, + 0.008545443447476042, + 0.933894891045596, + 0.7755600317402185, + 0.6440822804126228, + 0.5360434596838186, + 0.4464383812488555, + 0.369163156930965, + 0.3059268754196423, + 0.2535555148629677, + 0.21351400842336568, + 0.17737899041689556, + 0.1488127937496185, + 0.12451931880607947, + 0.10510895440395532, + 0.08997131172556919, + 0.07544405786485991, + 0.06384667032899957, + 0.05359213819202832, + 0.04529085027162302, + 0.040041506439602026, + 0.03528047366172252, + 0.032716840627479704, + 0.027467496795458707, + 0.02527009705182201, + 0.021363608618690105, + 0.01867789782091192 + ] + } + ], + "sigma": 0.001 + } +] \ No newline at end of file diff --git a/todo.md b/todo.md index 2786e27..1aa0a45 100644 --- a/todo.md +++ b/todo.md @@ -35,3 +35,8 @@ nginx: [warn] the "user" directive makes sense only if the master process runs w nginx: the configuration file /opt/homebrew/etc/nginx/nginx.conf syntax is ok ``` +2. 方案 & PLAN +✅ + +3. 使用Figma对重构UI + diff --git a/web/index.html b/web/index.html index 0d41800..967f232 100644 --- a/web/index.html +++ b/web/index.html @@ -6,7 +6,7 @@ 光纤延时等效采样 · 教学实验 - + @@ -42,36 +42,109 @@
-

动手实验:直接采样与寿命拟合(M0)

-

拖动参数,观察 10 ns 直接采样点数量与拟合寿命的变化——这正是四相位等效采样要解决的问题:50 ns 量级的衰减在 10 ns 采样下只有寥寥数点。

-
- - - - - - +

动手实验

+
+ + + + +
-
-
-
—
拟合寿命 τ̂ (ns)
-
—
相对偏差
-
—
采样点数
-
—
随机种子
+ + +
+

拖动参数,观察 10 ns 直接采样点数量与拟合寿命的变化——四相位等效采样要解决的正是在此。

+
+ + + + + + +
+
+
+
—
拟合寿命 τ̂ (ns)
+
—
相对偏差
+
—
采样点数
+
—
随机种子
+
+
+ + +
+

输入光纤长度(m)→ 自动计算传播延时与等效采样相位;也可反向设计:输入目标相位 → 得到光纤长度。

+
+ + + 1.468 + + +
+
+
+
+
+
+
+
+ + +
+

向四通道注入增益失配 / 延时误差 / 基线偏置,比较「不校准 / 基线+增益校准 / 完整校准」三种处理的重建曲线与寿命拟合。

+
+ + + + + 50 dB +
+
+
+
+ + +
+

同一数据上切换拟合算法:非线性最小二乘(NLS)与对数线性(默认尾段估基线)——观察对数变换对低幅值尾部噪声的放大。

+
+ + 50 dB + +
+
+
+
+ + +
+

蒙特卡洛重复实验:单通道 10 ns 直接采样 vs 四相位 2.5 ns 等效采样 的 τ₂ 拟合分布——等效采样显著提高寿命估计的稳定性。

+
+ + + 50 dB + +
+
+
@@ -80,9 +153,11 @@

结果解读

@@ -103,6 +178,6 @@ - + - + \ No newline at end of file diff --git a/web/js/app.js b/web/js/app.js index 1e30059..b73ac7d 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -1,4 +1,4 @@ -/* app.js:Pyodide 加载同一 core/ 算法核心 → ECharts 渲染 M0 交互演示 */ +/* app.js:Pyodide 加载同一 core/ 算法核心 → ECharts 渲染五个里程碑交互页 */ const CORE_FILES = [ "fiber_delay_sim/__init__.py", @@ -7,59 +7,115 @@ const CORE_FILES = [ "fiber_delay_sim/core/fiber.py", "fiber_delay_sim/core/acquisition.py", "fiber_delay_sim/core/fitting.py", + "fiber_delay_sim/core/calibration.py", + "fiber_delay_sim/core/statistics.py", "fiber_delay_sim/pipeline.py", ]; -// 浏览器侧包装函数:调用 pipeline.run_m0,输出轻量 JSON(连续曲线降采样) const PY_WRAPPER = ` import json import numpy as np from fiber_delay_sim import pipeline +from fiber_delay_sim.core import calibration, fitting, signal, fiber, statistics, acquisition def run_m0_web(tau, window_ns, snr_db, bits, seed): - params = { - "preset": "single", - "tau": float(tau), - "window_ns": float(window_ns), - "snr_db": None if snr_db is None else float(snr_db), - "bits": None if bits is None else int(bits), - } + params = {"preset": "single", "tau": float(tau), "window_ns": float(window_ns), + "snr_db": None if snr_db is None else float(snr_db), + "bits": None if bits is None else int(bits)} rec = pipeline.run_m0(params, seed=int(seed)) - step = max(1, len(rec["t_cont"]) // 4000) # 连续曲线降采样至 ~4000 点 + step = max(1, len(rec["t_cont"]) // 4000) return json.dumps({ - "t_cont": rec["t_cont"][::step].tolist(), - "y_cont": rec["y_cont"][::step].tolist(), - "t_samples": rec["t_samples"].tolist(), - "y_samples": rec["y_samples"].tolist(), - "tau_hat": rec["tau_hat"], - "tau_true": rec["tau_true"], - "rel_error": rec["rel_error"], - "n_samples": rec["n_samples"], - "A": rec["fit"]["A"], - "B": rec["fit"]["B"], + "t_cont": rec["t_cont"][::step].tolist(), "y_cont": rec["y_cont"][::step].tolist(), + "t_samples": rec["t_samples"].tolist(), "y_samples": rec["y_samples"].tolist(), + "tau_hat": rec["tau_hat"], "tau_true": rec["tau_true"], "rel_error": rec["rel_error"], + "n_samples": rec["n_samples"], "A": rec["fit"]["A"], "B": rec["fit"]["B"], "rmse": rec["fit"]["rmse"], }) + +def m1_forward_web(lengths, ng): + fwd = fiber.forward_design(lengths_m=[float(x) for x in lengths], n_g=float(ng)) + return json.dumps({ + "channels": [{"index": c["index"], "length_m": c["length_m"], + "delay_ns": c["delay_ns"], "phase_ns": c["phase_ns"]} for c in fwd["channels"]], + "sorted": fwd["sorted_phases_ns"], "dt": fwd["dt_ns"], + "uniformity": fwd["uniformity"], + }) + +def m1_inverse_web(targets, ng): + inv = fiber.inverse_design([float(x) for x in targets], n_g=float(ng)) + return json.dumps({ + "targets": inv["target_phases_ns"], "uniform": inv["is_uniform_grid"], + "construction": inv["construction"], + "recommended": inv["recommended"], + "candidates": inv["candidates"], + }) + +def m2_web(gain_amp, delay_amp, base_amp, snr, seed): + p = dict(pipeline.M2_DEFAULTS) + p["gain_errors"] = [0.0, 0.10*gain_amp, -0.08*gain_amp, 0.06*gain_amp] + p["delay_errors"] = [0.0, 0.5*delay_amp, -0.4*delay_amp, 0.3*delay_amp] + p["baselines"] = [0.0, 0.02*base_amp, -0.015*base_amp, 0.01*base_amp] + p["snr_db"] = float(snr) + rec = pipeline.run_m2(p, int(seed)) + def pick(key, skip=2): + d = rec[key] + return {"t": d["t"][::skip].tolist(), "y": d["y"][::skip].tolist(), + "tau": d["tau_hat"], "n": d["n_points"], "jump": d["continuity"]["mean_jump"]} + return json.dumps({ + "tau_true": rec["tau_true"], + "raw": pick("raw"), "nominal": pick("nominal"), "calibrated": pick("calibrated"), + }) + +def m3_web(snr, seed): + t = np.arange(0.0, 400.0, 10.0) + y = np.exp(-t / 52.8) + sigma = np.max(y) * 10 ** (-float(snr) / 20) + rng = np.random.default_rng(int(seed)) + yn = y + rng.normal(0, sigma, len(t)) + r1 = fitting.fit_single_exp_nls(t, yn) + r2 = fitting.fit_log_linear(t, yn) + return json.dumps({ + "t": t.tolist(), "y": yn.tolist(), "true": 52.8, + "nls": {"tau": r1["tau"], "A": r1["A"], "B": r1["B"]}, + "ll": {"tau": r2["tau"], "A": r2["A"], "B_est": r2["B_est"], + "dropped": r2["dropped_points"]}, + }) + +def m4_web(repeats, snr, seed): + cmp = pipeline.run_m4_compare(repeats=int(repeats), seed=int(seed), snr_db=float(snr)) + out = {"tau_true": cmp["tau_true"]} + for k in ("single", "fiber"): + st = cmp[k] + out[k] = {"tau_hats": st["tau_hats"], + "rel_std": (st["rel_std"] * 100 if st["rel_std"] else None), + "bias": (st.get("bias", 0) * 100 if st.get("bias") is not None else None), + "n_failed": st["n_failed"], "n": st["n"], + "failure_rate": st.get("failure_rate")} + return json.dumps(out) `; let pyodide = null; -let pyRunM0 = null; -let chart = null; let seed = 42; -let running = false; -let pending = false; - -const $ = (id) => document.getElementById(id); function setLoading(text) { $("loadingText").textContent = text; } +const $ = (id) => document.getElementById(id); + +/* ---------- ECharts 实例 ---------- */ +let charts = {}; +function getChart(id) { + if (!charts[id]) charts[id] = echarts.init($(id)); + return charts[id]; +} + +/* ---------- Pyodide ---------- */ async function initPyodide() { setLoading("正在加载 Pyodide 运行时…"); pyodide = await loadPyodide(); setLoading("正在加载 numpy / scipy(约 40 MB,首次较慢)…"); await pyodide.loadPackage(["numpy", "scipy"]); - setLoading("正在加载算法核心(fiber_delay_sim)…"); - pyodide.runPython("import sys; sys.path.insert(0, '/')"); // 使 FS 根下的 fiber_delay_sim 可导入 + pyodide.runPython("import sys; sys.path.insert(0, '/')"); for (const rel of CORE_FILES) { const res = await fetch("py/" + rel); if (!res.ok) throw new Error(`加载 ${rel} 失败:HTTP ${res.status}`); @@ -68,129 +124,326 @@ async function initPyodide() { pyodide.runPython(`import os; os.makedirs("/${dir}", exist_ok=True)`); pyodide.FS.writeFile("/" + rel, code); } - pyodide.runPython(PY_WRAPPER); - pyRunM0 = pyodide.globals.get("run_m0_web"); - + // Pyodide 在文件写入后立即 import 偶发失败:清缓存 + 失败重试一次 + pyodide.runPython("import importlib; importlib.invalidate_caches()"); + try { + pyodide.runPython(PY_WRAPPER); + } catch (e) { + console.warn("wrapper 首次加载失败,重试…", e); + await new Promise((r) => setTimeout(r, 200)); + pyodide.runPython("import importlib; importlib.invalidate_caches()"); + pyodide.runPython(PY_WRAPPER); + } $("loading").classList.add("hidden"); } -function readParams() { +async function callPy(name, args) { + let fn = pyodide.globals.get(name); + if (fn === undefined) { + // 防御:首次注册可能受 Pyodide 文件导入时序影响,重新执行一次 wrapper + console.warn("注册函数缺失,重新执行 wrapper:", name); + pyodide.runPython("import importlib; importlib.invalidate_caches()"); + pyodide.runPython(eval("PY_WRAPPER")); + fn = pyodide.globals.get(name); + if (fn === undefined) throw new Error(`Python 函数 ${name} 注册失败`); + } + const out = await fn(...args); + return JSON.parse(out); +} + +/* ---------------- 通用绘图基元 ---------------- */ +function baseLineOption() { return { + grid: { left: 62, right: 26, top: 44, bottom: 46 }, + tooltip: { trigger: "axis" }, + xAxis: { name: "时间 (ns)", nameLocation: "middle", nameGap: 30, type: "value", + splitLine: { lineStyle: { color: "#e8edf2" } } }, + yAxis: { name: "归一化强度", type: "value", + splitLine: { lineStyle: { color: "#e8edf2" } } }, + }; +} + +/* ================= M0 ================= */ +async function runM0() { + const p = { tau: parseFloat($("tau").value), window: parseFloat($("window").value), snr: $("noNoise").checked ? null : parseFloat($("snr").value), bits: $("noNoise").checked ? null : parseInt($("bits").value, 10), }; -} - -function fmt(x, digits = 3) { - if (x === null || x === undefined || Number.isNaN(x)) return "—"; - return Number(x).toFixed(digits); -} - -function updateChart(out) { + const out = await callPy("run_m0_web", [p.tau, p.window, p.snr, p.bits, seed]); const tFit = out.t_samples; const yFit = tFit.map((t) => out.A * Math.exp(-t / out.tau_hat) + out.B); - const option = { - grid: { left: 62, right: 26, top: 44, bottom: 46 }, - tooltip: { trigger: "axis" }, - legend: { - top: 8, - data: ["连续信号(真值)", "10 ns 采样点", "NLS 拟合"], - }, - xAxis: { - name: "时间 (ns)", nameLocation: "middle", nameGap: 30, - type: "value", - axisLine: { lineStyle: { color: "#8ea2b5" } }, - splitLine: { lineStyle: { color: "#e8edf2" } }, - }, - yAxis: { - name: "归一化强度", type: "value", - axisLine: { lineStyle: { color: "#8ea2b5" } }, - splitLine: { lineStyle: { color: "#e8edf2" } }, - }, + getChart("chartM0").setOption({ + ...baseLineOption(), + legend: { top: 8, data: ["连续信号(真值)", "10 ns 采样点", "NLS 拟合"] }, series: [ - { - name: "连续信号(真值)", type: "line", showSymbol: false, + { name: "连续信号(真值)", type: "line", showSymbol: false, data: out.t_cont.map((t, i) => [t, out.y_cont[i]]), - lineStyle: { color: "#9aa5b1", width: 1.5 }, - silent: true, - }, - { - name: "10 ns 采样点", type: "scatter", + lineStyle: { color: "#9aa5b1", width: 1.5 }, silent: true }, + { name: "10 ns 采样点", type: "scatter", data: out.t_samples.map((t, i) => [t, out.y_samples[i]]), - symbolSize: 7, itemStyle: { color: "#C25B2A" }, - }, - { - name: "NLS 拟合", type: "line", showSymbol: false, + symbolSize: 7, itemStyle: { color: "#C25B2A" } }, + { name: "NLS 拟合", type: "line", showSymbol: false, data: tFit.map((t, i) => [t, yFit[i]]), - lineStyle: { color: "#2D5F8A", width: 2, type: "dashed" }, - silent: true, - }, + lineStyle: { color: "#2D5F8A", width: 2, type: "dashed" }, silent: true }, ], - }; - chart.setOption(option, true); -} - -function updateResults(out) { - $("tauHat").textContent = fmt(out.tau_hat); - $("relErr").textContent = - out.rel_error < 1e-4 ? out.rel_error.toExponential(1) : fmt(out.rel_error * 100, 2) + "%"; + }, true); + $("tauHat").textContent = out.tau_hat.toFixed(3); + $("relErr").textContent = out.rel_error < 1e-4 ? out.rel_error.toExponential(1) : (out.rel_error * 100).toFixed(2) + "%"; $("nPts").textContent = out.n_samples; $("seedLbl").textContent = seed; } -async function run() { - if (!pyRunM0) return; - if (running) { pending = true; return; } - running = true; - const p = readParams(); - try { - const json = await pyRunM0(p.tau, p.window, p.snr, p.bits, seed); - const out = JSON.parse(json); - updateChart(out); - updateResults(out); - } catch (e) { - console.error(e); - alert("运行出错:" + e.message); - } finally { - running = false; - if (pending) { pending = false; run(); } +/* ================= M1 ================= */ +function m1Inputs() { + const n = parseInt($("m1N").value, 10); + const box = $("m1Inputs"); + let html = ""; + for (let i = 0; i < n; i++) { + const def = [0, 9.7, 19.4, 29.1][i] ?? 5.0 * (i + 1); + html += ``; } + box.innerHTML = html; +} + +function m1TableHtml(out) { + const u = out.uniformity; + let h = ``; + for (const c of out.channels) { + h += ``; + } + h += `
通道长度 (m)延时 (ns)相位 (ns)
CH${c.index + 1}${c.length_m.toFixed(3)}${c.delay_ns.toFixed(3)}${c.phase_ns.toFixed(3)}

等效采样网格:${out.sorted.map((x) => x.toFixed(2)).join(" / ")} ns(理想步长 ${u.ideal_step_ns} ns,最大间隔偏差 ${u.max_gap_dev_ns.toExponential(1)})

`; + return h; +} + +async function m1Forward() { + const lens = [...document.querySelectorAll(".m1len")].map((el) => parseFloat(el.value)); + const ng = parseFloat($("m1Ng").value); + const out = await callPy("m1_forward_web", [lens, ng]); + const ch = out.channels; + getChart("chartM1a").setOption({ + grid: { left: 46, right: 96, top: 40, bottom: 42 }, + tooltip: {}, + xAxis: { type: "value", name: "延时 (ns)", min: 0, max: 165, interval: 20, + axisLabel: { fontSize: 11 } }, + yAxis: { type: "category", data: ch.map((c) => `CH${c.index + 1}`), + splitLine: { show: false } }, + series: [{ + type: "scatter", symbolSize: 24, + data: ch.map((c) => ({ value: [c.delay_ns, c.index], name: `CH${c.index + 1}` })), + itemStyle: { color: "#2D5F8A" }, + label: { show: true, formatter: (p) => `${p.value[0].toFixed(1)} ns`, position: "right", fontSize: 11 }, + }], + }, true); + // 相位图(一个采样周期内) + getChart("chartM1b").setOption({ + grid: { left: 46, right: 26, top: 30, bottom: 54 }, + tooltip: {}, + xAxis: { type: "value", name: "相位 (ns)", nameLocation: "middle", nameGap: 34, + min: 0, max: 10, interval: 2.5, axisLabel: { fontSize: 11 } }, + yAxis: { show: false, min: 0, max: 1.2 }, + series: [{ + type: "scatter", symbolSize: 22, + data: ch.map((c) => [c.phase_ns, 0.6]), + itemStyle: { color: "#C25B2A" }, + label: { show: true, formatter: (p) => `CH${p.dataIndex + 1} φ=${p.value[0].toFixed(2)}ns`, position: "top", fontSize: 11 }, + }], + }, true); + $("m1Table").innerHTML = m1TableHtml(out); +} + +async function m1Inverse() { + const targets = [...document.querySelectorAll(".m1len")].map((el) => parseFloat(el.value)); + const ng = parseFloat($("m1Ng").value); + const out = await callPy("m1_inverse_web", [targets, ng]); + if (!out.uniform) { + $("m1Table").innerHTML = `

目标相位非均匀网格(${out.targets.map((x) => x.toFixed(1)).join(" / ")} ns)——等效网格将不均匀。建议使用均匀网格 j·Δt/N。

`; + return; + } + let h = `

构造式:${out.construction || "—"}

`; + for (const e of out.recommended) { + h += ``; + } + h += `
目标相位 (ns)通道序 k延时 (ns)光纤长度 (m)
${e.phase_ns.toFixed(2)}${e.k}${e.delay_ns.toFixed(2)}${e.length_m.toFixed(3)}

反算长度对应原项目名义四组:0 / 9.70 / 19.40 / 29.10 m

`; + $("m1Table").innerHTML = h; +} + +/* ================= M2 ================= */ +async function runM2() { + const ga = parseFloat($("m2g").value); + const da = parseFloat($("m2d").value); + const ba = parseFloat($("m2b").value); + const snr = parseFloat($("m2snr").value); + const out = await callPy("m2_web", [ga, da, ba, snr, seed]); + const series = [ + { name: "理论 I(t)", type: "line", showSymbol: false, + data: Array.from({ length: 200 }, (_, i) => [i * 2, Math.exp(-i * 2 / out.tau_true)]), + lineStyle: { color: "#111", width: 1.5 }, silent: true }, + { name: "不校准", type: "scatter", data: out.raw.t.map((t, i) => [t, out.raw.y[i]]), + symbolSize: 4, itemStyle: { color: "#C25B2A" } }, + { name: "基线+增益", type: "scatter", data: out.nominal.t.map((t, i) => [t, out.nominal.y[i]]), + symbolSize: 4, itemStyle: { color: "#6B2A35" } }, + { name: "完整校准", type: "scatter", data: out.calibrated.t.map((t, i) => [t, out.calibrated.y[i]]), + symbolSize: 4, itemStyle: { color: "#2D5F8A" } }, + ]; + getChart("chartM2").setOption({ + ...baseLineOption(), legend: { top: 8 }, + xAxis: { ...baseLineOption().xAxis, max: 200 }, + series, + }, true); + const row = (name, d) => { + const err = d.tau == null ? "—" : (Math.abs(d.tau - out.tau_true) / out.tau_true * 100).toFixed(2) + "%"; + return `${name}${d.tau == null ? "—" : d.tau.toFixed(3)}${err}${d.n}${d.jump.toFixed(5)}`; + }; + $("m2Table").innerHTML = ` + ${row("不校准", out.raw)}${row("基线+增益校准", out.nominal)}${row("完整校准", out.calibrated)}
方案τ̂ (ns)偏差点数连续度 mean_jump
+

真值 τ = ${out.tau_true} ns。校准显著降低通道断层(连续度),寿命拟合偏差在有模型自由度时被部分吸收——教学点。

`; +} + +/* ================= M3 ================= */ +async function runM3() { + const snr = parseFloat($("m3snr").value); + const out = await callPy("m3_web", [snr, seed]); + const t = out.t; + const yNls = t.map((x) => out.nls.A * Math.exp(-x / out.nls.tau) + out.nls.B); + const yLl = (out.ll.tau != null) ? t.map((x) => out.ll.A * Math.exp(-x / out.ll.tau)) : []; + const series = [ + { name: "真值", type: "line", showSymbol: false, data: t.map((x, i) => [x, out.y[i] * 0 + Math.exp(-x / out.true)]), + lineStyle: { color: "#111", width: 1.2 }, silent: true }, + { name: "采样数据", type: "scatter", data: t.map((x, i) => [x, out.y[i]]), symbolSize: 5, itemStyle: { color: "#9aa5b1" } }, + { name: "NLS", type: "line", showSymbol: false, data: t.map((x, i) => [x, yNls[i]]), + lineStyle: { color: "#2D5F8A", width: 2 }, silent: true }, + ]; + if (yLl.length) { + series.push({ name: "对数线性(估基线)", type: "line", showSymbol: false, + data: t.map((x, i) => [x, yLl[i]]), lineStyle: { color: "#C25B2A", width: 2, type: "dashed" }, silent: true }); + } + getChart("chartM3").setOption({ + grid: { left: 62, right: 26, top: 44, bottom: 46 }, + tooltip: { trigger: "axis" }, + xAxis: { name: "时间 (ns)", nameLocation: "middle", nameGap: 30, type: "value" }, + yAxis: { name: "归一化强度", type: "log" }, + legend: { top: 8 }, + series, + }, true); + const row = (name, r) => { + if (r.tau == null) return `${name}———`; + const err = Math.abs(r.tau - out.true) / out.true * 100; + return `${name}${r.tau.toFixed(3)}${err.toFixed(2)}%${(r.B_est ?? "—").toFixed(4)}`; + }; + $("m3result").innerHTML = ` + ${row("NLS", out.nls)}${row("对数线性(尾段估基线)", out.ll)}
算法τ̂ (ns)偏差估计基线 B
+

真值 52.8 ns。对数线性在估基线下有系统偏差;低幅值尾部经对数变换后噪声权重被放大。

`; +} + +/* ================= M4 ================= */ +async function runM4() { + const reps = parseInt($("m4repeats").value, 10); + const snr = parseFloat($("m4snr").value); + const out = await callPy("m4_web", [reps, snr, 0]); + const bins = []; + const minV = Math.min(...out.single.tau_hats, ...out.fiber.tau_hats, out.tau_true - 4); + const maxV = Math.max(...out.single.tau_hats, ...out.fiber.tau_hats, out.tau_true + 4); + const step = (maxV - minV) / 24; + for (let i = 0; i < 24; i++) bins.push(+(minV + i * step).toFixed(2)); + const hist = (vals) => { + const counts = new Array(24).fill(0); + for (const v of vals) { + const idx = Math.min(23, Math.max(0, Math.floor((v - minV) / step))); + counts[idx]++; + } + return counts.map((c, i) => [bins[i], c]); + }; + getChart("chartM4").setOption({ + grid: { left: 60, right: 26, top: 44, bottom: 46 }, + tooltip: { trigger: "axis" }, + xAxis: { name: "τ̂₂ (ns)", nameLocation: "middle", nameGap: 30, type: "value" }, + yAxis: { name: "次数", type: "value" }, + legend: { top: 8 }, + series: [ + { name: `单通道 σ/τ=${(out.single.rel_std ?? 0).toFixed(2)}%`, type: "bar", data: hist(out.single.tau_hats), itemStyle: { color: "#C25B2A" } }, + { name: `四相位 σ/τ=${(out.fiber.rel_std ?? 0).toFixed(2)}%`, type: "bar", data: hist(out.fiber.tau_hats), itemStyle: { color: "#2D5F8A" } }, + { name: `真值 ${out.tau_true}`, type: "line", data: [], markLine: { data: [{ xAxis: out.tau_true }], lineStyle: { color: "#111", type: "dashed" } }, silent: true }, + ], + }, true); + $("m4result").innerHTML = ` + +
方案σ/τbias拟合失败
单通道 10ns${(out.single.rel_std ?? 0).toFixed(2)}%${(out.single.bias ?? 0).toFixed(2)}%${out.single.n_failed}/${out.single.n}
四相位等效${(out.fiber.rel_std ?? 0).toFixed(2)}%${(out.fiber.bias ?? 0).toFixed(2)}%${out.fiber.n_failed}/${out.fiber.n}
+

${reps} 次蒙特卡洛(SNR ${snr} dB,窗口 400 ns,真值 52.8 ns)。浏览器计算,与本地 CLI 结果一致。

`; +} + +/* ---------------- 页面初始化 ---------------- */ +const TAB_RUN = { + "tab-m0": () => runM0(), + "tab-m1": () => m1Forward(), + "tab-m2": () => runM2(), + "tab-m3": () => runM3(), + "tab-m4": () => runM4(), +}; +const tabRan = { "tab-m0": false, "tab-m1": false, "tab-m2": false, + "tab-m3": false, "tab-m4": false }; + +function bindTabs() { + $("tabs").addEventListener("click", (e) => { + const btn = e.target.closest(".tab"); + if (!btn) return; + document.querySelectorAll(".tab").forEach((b) => b.classList.remove("active")); + document.querySelectorAll(".tabpane").forEach((p) => p.classList.remove("active")); + btn.classList.add("active"); + const paneId = btn.dataset.tab; // dataset.tab 即 pane 的 id(如 tab-m0) + $(paneId).classList.add("active"); + // 隐藏容器中初始化的图表尺寸为 0,切换后统一 resize + setTimeout(() => Object.values(charts).forEach((c) => c.resize()), 60); + if (!tabRan[paneId]) { + tabRan[paneId] = true; + try { TAB_RUN[paneId](); } catch (err) { console.error(paneId, err); } + } + }); } function bindControls() { - const refresh = () => run(); let timer = null; - const debounced = () => { clearTimeout(timer); timer = setTimeout(refresh, 250); }; + const debounce = (fn, ms = 250) => { clearTimeout(timer); timer = setTimeout(fn, ms); }; - $("tau").addEventListener("input", () => { - $("tauVal").textContent = $("tau").value; - debounced(); - }); - $("snr").addEventListener("input", () => { - $("snrVal").textContent = $("snr").value; - debounced(); - }); - $("window").addEventListener("change", debounced); - $("bits").addEventListener("change", debounced); - $("noNoise").addEventListener("change", debounced); - $("resample").addEventListener("click", () => { - seed = (Math.floor(Math.random() * 100000) + 1); - run(); - }); + $("tau").addEventListener("input", () => { $("tauVal").textContent = $("tau").value; debounce(runM0); }); + $("snr").addEventListener("input", () => { $("snrVal").textContent = $("snr").value; debounce(runM0); }); + $("window").addEventListener("change", debounce(runM0)); + $("bits").addEventListener("change", debounce(runM0)); + $("noNoise").addEventListener("change", debounce(runM0)); + $("resample").addEventListener("click", () => { seed = 1 + Math.floor(Math.random() * 99999); runM0(); }); - chart = echarts.init($("chart")); - window.addEventListener("resize", () => chart && chart.resize()); + $("m1N").addEventListener("change", m1Inputs); + $("m1Apply").addEventListener("click", m1Forward); + $("m1Inverse").addEventListener("click", m1Inverse); + $("m1Ng").addEventListener("input", () => { $("m1NgVal").textContent = $("m1Ng").value; }); + + $("m2g").addEventListener("input", () => { $("m2gVal").textContent = $("m2g").value; debounce(runM2, 300); }); + $("m2d").addEventListener("input", () => { $("m2dVal").textContent = $("m2d").value; debounce(runM2, 300); }); + $("m2b").addEventListener("input", () => { $("m2bVal").textContent = $("m2b").value; debounce(runM2, 300); }); + $("m2snr").addEventListener("input", () => { $("m2snrVal").textContent = $("m2snr").value; debounce(runM2, 300); }); + + $("m3snr").addEventListener("input", () => { $("m3snrVal").textContent = $("m3snr").value; debounce(runM3, 300); }); + $("m3resample").addEventListener("click", () => { seed = 1 + Math.floor(Math.random() * 99999); runM3(); }); + + $("m4snr").addEventListener("input", () => { $("m4snrVal").textContent = $("m4snr").value; }); + $("m4run").addEventListener("click", runM4); + + window.addEventListener("resize", () => Object.values(charts).forEach((c) => c.resize())); } (async function main() { + bindTabs(); bindControls(); + m1Inputs(); try { await initPyodide(); - await run(); + // 仅渲染当前可见的 M0 tab;其余 tab 首次切换时惰性渲染(避免隐藏容器尺寸为 0) + tabRan["tab-m0"] = true; + await runM0(); + await runM4(); } catch (e) { console.error(e); setLoading("加载失败:" + e.message + "(请刷新重试,或检查网络对 cdn.jsdelivr.net 的访问)"); } -})(); +})(); \ No newline at end of file diff --git a/web/js/style.css b/web/js/style.css index 1cbda09..6a04bbf 100644 --- a/web/js/style.css +++ b/web/js/style.css @@ -114,3 +114,22 @@ footer p { font-size: 12.5px; color: var(--muted); margin-bottom: 6px; } .chart { height: 320px; } .brand h1 { font-size: 18px; } } + +/* tabs */ +.tabs { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 16px; } +.tab { + border: 1px solid var(--line); background: #fff; color: var(--text); + border-radius: 8px; padding: 7px 14px; font-size: 13.5px; cursor: pointer; +} +.tab:hover { border-color: var(--accent); } +.tab.active { background: var(--primary); color: #fff; border-color: var(--primary); } + +.tabpane { display: none; } +.tabpane.active { display: block; } + +/* tables */ +.table-wrap { margin-top: 14px; overflow-x: auto; } +.tbl { border-collapse: collapse; width: 100%; font-size: 13px; } +.tbl th, .tbl td { border: 1px solid var(--line); padding: 6px 10px; text-align: center; } +.tbl th { background: #f2f6fa; color: var(--primary); } +.note { font-size: 12.5px; color: var(--muted); margin-top: 8px; } diff --git a/web/py/fiber_delay_sim/__init__.py b/web/py/fiber_delay_sim/__init__.py index e17aab6..be8aa01 100644 --- a/web/py/fiber_delay_sim/__init__.py +++ b/web/py/fiber_delay_sim/__init__.py @@ -5,5 +5,5 @@ (约束见 docs/实现方案.md §5.1)。 """ -__version__ = "0.1.0" -ALGO_VERSION = "M0+M1" +__version__ = "0.5.0" +ALGO_VERSION = "M0-M4" diff --git a/web/py/fiber_delay_sim/core/__init__.py b/web/py/fiber_delay_sim/core/__init__.py index c00b203..70d0ce4 100644 --- a/web/py/fiber_delay_sim/core/__init__.py +++ b/web/py/fiber_delay_sim/core/__init__.py @@ -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"] \ No newline at end of file diff --git a/web/py/fiber_delay_sim/core/acquisition.py b/web/py/fiber_delay_sim/core/acquisition.py index 92facec..2c848bd 100644 --- a/web/py/fiber_delay_sim/core/acquisition.py +++ b/web/py/fiber_delay_sim/core/acquisition.py @@ -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, + } diff --git a/web/py/fiber_delay_sim/core/calibration.py b/web/py/fiber_delay_sim/core/calibration.py new file mode 100644 index 0000000..1c00999 --- /dev/null +++ b/web/py/fiber_delay_sim/core/calibration.py @@ -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))), + } \ No newline at end of file diff --git a/web/py/fiber_delay_sim/core/statistics.py b/web/py/fiber_delay_sim/core/statistics.py new file mode 100644 index 0000000..5717f35 --- /dev/null +++ b/web/py/fiber_delay_sim/core/statistics.py @@ -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} \ No newline at end of file diff --git a/web/py/fiber_delay_sim/pipeline.py b/web/py/fiber_delay_sim/pipeline.py index 5a23e65..130ae50 100644 --- a/web/py/fiber_delay_sim/pipeline.py +++ b/web/py/fiber_delay_sim/pipeline.py @@ -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, + }