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

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

View File

@@ -6,7 +6,7 @@
<title>光纤延时等效采样 · 教学实验</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.js"></script>
<link rel="stylesheet" href="js/style.css">
<link rel="stylesheet" href="js/style.css?v=3">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='80' font-size='80'%3E%F0%9F%93%8F%3C/text%3E%3C/svg%3E">
</head>
<body>
@@ -42,36 +42,109 @@
<section id="demo" class="wrap">
<div class="card">
<h2>动手实验:直接采样与寿命拟合(M0)</h2>
<p class="hint">拖动参数,观察 10 ns 直接采样点数量与拟合寿命的变化——这正是四相位等效采样要解决的问题:50 ns 量级的衰减在 10 ns 采样下只有寥寥数点。</p>
<div class="controls">
<label>荧光寿命 τ <span id="tauVal" class="val">52.8</span> ns
<input id="tau" type="range" min="10" max="100" step="0.5" value="52.8"></label>
<label>信噪比 SNR <span id="snrVal" class="val">50</span> dB
<input id="snr" type="range" min="20" max="80" step="1" value="50"></label>
<label>记录窗口
<select id="window">
<option value="40">40 ns(≈0.76τ,仅 4 点)</option>
<option value="100">100 ns</option>
<option value="200">200 ns</option>
<option value="400" selected>400 ns(40 点)</option>
</select></label>
<label>ADC 位数
<select id="bits">
<option value="8">8 bit</option>
<option value="10">10 bit</option>
<option value="12" selected>12 bit</option>
<option value="14">14 bit</option>
</select></label>
<label class="chk"><input id="noNoise" type="checkbox"> 理想无噪</label>
<button id="resample" class="btn" title="换一个随机种子重新采样">重新采样 ↻</button>
<h2>动手实验</h2>
<div class="tabs" id="tabs">
<button class="tab active" data-tab="tab-m0">M0 直接采样</button>
<button class="tab" data-tab="tab-m1">M1 光纤设计</button>
<button class="tab" data-tab="tab-m2">M2 校准与重建</button>
<button class="tab" data-tab="tab-m3">M3 算法对比</button>
<button class="tab" data-tab="tab-m4">M4 统计</button>
</div>
<div id="chart" class="chart"></div>
<div class="results" id="results">
<div class="res-item"><div class="res-num" id="tauHat">—</div><div class="res-lbl">拟合寿命 τ̂ (ns)</div></div>
<div class="res-item"><div class="res-num" id="relErr">—</div><div class="res-lbl">相对偏差</div></div>
<div class="res-item"><div class="res-num" id="nPts">—</div><div class="res-lbl">采样点数</div></div>
<div class="res-item"><div class="res-num" id="seedLbl">—</div><div class="res-lbl">随机种子</div></div>
<!-- ===================== M0 ===================== -->
<div class="tabpane active" id="tab-m0">
<p class="hint">拖动参数,观察 10 ns 直接采样点数量与拟合寿命的变化——四相位等效采样要解决的正是在此。</p>
<div class="controls">
<label>荧光寿命 τ <span id="tauVal" class="val">52.8</span> ns
<input id="tau" type="range" min="10" max="100" step="0.5" value="52.8"></label>
<label>信噪比 SNR <span id="snrVal" class="val">50</span> dB
<input id="snr" type="range" min="20" max="80" step="1" value="50"></label>
<label>记录窗口
<select id="window">
<option value="40">40 ns(≈0.76τ,仅 4 点)</option>
<option value="100">100 ns</option>
<option value="200">200 ns</option>
<option value="400" selected>400 ns(40 点)</option>
</select></label>
<label>ADC 位数
<select id="bits">
<option value="8">8 bit</option>
<option value="10">10 bit</option>
<option value="12" selected>12 bit</option>
<option value="14">14 bit</option>
</select></label>
<label class="chk"><input id="noNoise" type="checkbox"> 理想无噪</label>
<button id="resample" class="btn">重新采样 ↻</button>
</div>
<div id="chartM0" class="chart"></div>
<div class="results">
<div class="res-item"><div class="res-num" id="tauHat">—</div><div class="res-lbl">拟合寿命 τ̂ (ns)</div></div>
<div class="res-item"><div class="res-num" id="relErr">—</div><div class="res-lbl">相对偏差</div></div>
<div class="res-item"><div class="res-num" id="nPts">—</div><div class="res-lbl">采样点数</div></div>
<div class="res-item"><div class="res-num" id="seedLbl">—</div><div class="res-lbl">随机种子</div></div>
</div>
</div>
<!-- ================= M1 光纤设计 ================= -->
<div class="tabpane" id="tab-m1">
<p class="hint">输入光纤长度(m)→ 自动计算传播延时与等效采样相位;也可反向设计:输入目标相位 → 得到光纤长度。</p>
<div class="controls">
<label>通道数
<select id="m1N"><option value="2">2</option><option value="3">3</option><option value="4" selected>4</option></select></label>
<label>群折射率 n_g <input id="m1Ng" type="range" min="1.44" max="1.50" step="0.001" value="1.468"></label>
<span class="val" id="m1NgVal">1.468</span>
<button id="m1Apply" class="btn">正向计算 →</button>
<button id="m1Inverse" class="btn">反向设计 ←</button>
</div>
<div id="m1Inputs" class="controls"></div>
<div style="display:flex;gap:16px;flex-wrap:wrap">
<div id="chartM1a" style="width:46%;min-width:320px;height:340px"></div>
<div id="chartM1b" style="width:46%;min-width:320px;height:340px"></div>
</div>
<div id="m1Table" class="table-wrap"></div>
</div>
<!-- ================= M2 校准与重建 ================= -->
<div class="tabpane" id="tab-m2">
<p class="hint">向四通道注入增益失配 / 延时误差 / 基线偏置,比较「不校准 / 基线+增益校准 / 完整校准」三种处理的重建曲线与寿命拟合。</p>
<div class="controls">
<label>通道增益失配 <span id="m2gVal" class="val">1.0</span>
<input id="m2g" type="range" min="0" max="1.5" step="0.05" value="1.0"></label>
<label>延时误差 <span id="m2dVal" class="val">1.0</span>
<input id="m2d" type="range" min="0" max="2" step="0.1" value="1.0"></label>
<label>基线偏置 <span id="m2bVal" class="val">1.0</span>
<input id="m2b" type="range" min="0" max="2" step="0.1" value="1.0"></label>
<label>SNR <input id="m2snr" type="range" min="20" max="70" step="1" value="50"></label>
<span class="val" id="m2snrVal">50</span> dB
</div>
<div id="chartM2" class="chart"></div>
<div id="m2Table" class="table-wrap"></div>
</div>
<!-- ================= M3 算法对比 ================= -->
<div class="tabpane" id="tab-m3">
<p class="hint">同一数据上切换拟合算法:非线性最小二乘(NLS)与对数线性(默认尾段估基线)——观察对数变换对低幅值尾部噪声的放大。</p>
<div class="controls">
<label>SNR <input id="m3snr" type="range" min="20" max="70" step="1" value="50"></label>
<span class="val" id="m3snrVal">50</span> dB
<button id="m3resample" class="btn">重新采样 ↻</button>
</div>
<div id="chartM3" class="chart" style="height:380px"></div>
<div id="m3result" class="table-wrap"></div>
</div>
<!-- ================= M4 统计 ================= -->
<div class="tabpane" id="tab-m4">
<p class="hint">蒙特卡洛重复实验:单通道 10 ns 直接采样 vs 四相位 2.5 ns 等效采样 的 τ₂ 拟合分布——等效采样显著提高寿命估计的稳定性。</p>
<div class="controls">
<label>重复次数
<select id="m4repeats"><option value="30">30</option><option value="60" selected>60</option><option value="120">120</option></select></label>
<label>SNR <input id="m4snr" type="range" min="30" max="60" step="1" value="50"></label>
<span class="val" id="m4snrVal">50</span> dB
<button id="m4run" class="btn">运行蒙特卡洛</button>
</div>
<div id="chartM4" class="chart" style="height:400px"></div>
<div id="m4result" class="table-wrap"></div>
</div>
</div>
</section>
@@ -80,9 +153,11 @@
<div class="card">
<h2>结果解读</h2>
<ul>
<li><strong>点数不足</strong>:把窗口调到 40 ns(约 0.76τ),只有 4 个采样点——信号才衰减到初值的 47%,拟合结果将随噪声大幅波动;</li>
<li><strong>信噪比</strong>:降低 SNR 观察拟合值抖动增大;理想无噪下 NLS 拟合应精确复现设定寿命(相对偏差 ≈ 0,即原项目的"标准拟合"基准验证);</li>
<li><strong>四相位等效采样</strong>如何解决点数问题、通道误差与校准的作用,将在后续里程碑(M2–M5)陆续上线。</li>
<li><strong>M0 点数不足</strong>:把窗口调到 40 ns(约 0.76τ),只有 4 个采样点——信号才衰减到初值的 47%,拟合结果随噪声大幅波动;</li>
<li><strong>M1 光学游标卡尺</strong>:光纤长度 → 传播延时 → 对 10 ns 采样周期取余得到不同相位;目标 0/2.5/5/7.5 ns 的均匀网格可反推出 0/9.70/19.40/29.10 m;</li>
<li><strong>M2 校准价值</strong>:注入增益/延时/基线误差后,不校准的重建曲线出现通道断层;基线+增益校准显著改善连续度(延时常数错位不改变单指数 τ——教学点);</li>
<li><strong>M3 算法选择</strong>:NLS 稳健;对数线性需准确基线,默认尾段估基线会引入系统偏差;</li>
<li><strong>M4 统计收益</strong>:四相位等效采样的 τ₂ 蒙特卡洛分布明显比单通道窄,失败率更低。</li>
</ul>
</div>
</section>
@@ -103,6 +178,6 @@
</div>
</div>
<script src="js/app.js"></script>
<script src="js/app.js?v=7"></script>
</body>
</html>
</html>

View File

@@ -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 += `<label>光纤 L${i} (m) <input class="m1len" type="number" step="0.1" value="${def}"></label>`;
}
box.innerHTML = html;
}
function m1TableHtml(out) {
const u = out.uniformity;
let h = `<table class="tbl"><tr><th>通道</th><th>长度 (m)</th><th>延时 (ns)</th><th>相位 (ns)</th></tr>`;
for (const c of out.channels) {
h += `<tr><td>CH${c.index + 1}</td><td>${c.length_m.toFixed(3)}</td><td>${c.delay_ns.toFixed(3)}</td><td>${c.phase_ns.toFixed(3)}</td></tr>`;
}
h += `</table><p class="note">等效采样网格:${out.sorted.map((x) => x.toFixed(2)).join(" / ")} ns(理想步长 ${u.ideal_step_ns} ns,最大间隔偏差 ${u.max_gap_dev_ns.toExponential(1)})</p>`;
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 = `<p class="note">目标相位非均匀网格(${out.targets.map((x) => x.toFixed(1)).join(" / ")} ns)——等效网格将不均匀。建议使用均匀网格 j·Δt/N。</p>`;
return;
}
let h = `<p class="note">构造式:${out.construction || "—"}</p><table class="tbl"><tr><th>目标相位 (ns)</th><th>通道序 k</th><th>延时 (ns)</th><th>光纤长度 (m)</th></tr>`;
for (const e of out.recommended) {
h += `<tr><td>${e.phase_ns.toFixed(2)}</td><td>${e.k}</td><td>${e.delay_ns.toFixed(2)}</td><td>${e.length_m.toFixed(3)}</td></tr>`;
}
h += `</table><p class="note">反算长度对应原项目名义四组:0 / 9.70 / 19.40 / 29.10 m</p>`;
$("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 `<tr><td>${name}</td><td>${d.tau == null ? "—" : d.tau.toFixed(3)}</td><td>${err}</td><td>${d.n}</td><td>${d.jump.toFixed(5)}</td></tr>`;
};
$("m2Table").innerHTML = `<table class="tbl"><tr><th>方案</th><th>τ̂ (ns)</th><th>偏差</th><th>点数</th><th>连续度 mean_jump</th></tr>
${row("不校准", out.raw)}${row("基线+增益校准", out.nominal)}${row("完整校准", out.calibrated)}</table>
<p class="note">真值 τ = ${out.tau_true} ns。校准显著降低通道断层(连续度),寿命拟合偏差在有模型自由度时被部分吸收——教学点。</p>`;
}
/* ================= 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 `<tr><td>${name}</td><td>—</td><td>—</td><td>—</td></tr>`;
const err = Math.abs(r.tau - out.true) / out.true * 100;
return `<tr><td>${name}</td><td>${r.tau.toFixed(3)}</td><td>${err.toFixed(2)}%</td><td>${(r.B_est ?? "—").toFixed(4)}</td></tr>`;
};
$("m3result").innerHTML = `<table class="tbl"><tr><th>算法</th><th>τ̂ (ns)</th><th>偏差</th><th>估计基线 B</th></tr>
${row("NLS", out.nls)}${row("对数线性(尾段估基线)", out.ll)}</table>
<p class="note">真值 52.8 ns。对数线性在估基线下有系统偏差;低幅值尾部经对数变换后噪声权重被放大。</p>`;
}
/* ================= 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 = `<table class="tbl"><tr><th>方案</th><th>σ/τ</th><th>bias</th><th>拟合失败</th></tr>
<tr><td>单通道 10ns</td><td>${(out.single.rel_std ?? 0).toFixed(2)}%</td><td>${(out.single.bias ?? 0).toFixed(2)}%</td><td>${out.single.n_failed}/${out.single.n}</td></tr>
<tr><td>四相位等效</td><td>${(out.fiber.rel_std ?? 0).toFixed(2)}%</td><td>${(out.fiber.bias ?? 0).toFixed(2)}%</td><td>${out.fiber.n_failed}/${out.fiber.n}</td></tr></table>
<p class="note">${reps} 次蒙特卡洛(SNR ${snr} dB,窗口 400 ns,真值 52.8 ns)。浏览器计算,与本地 CLI 结果一致。</p>`;
}
/* ---------------- 页面初始化 ---------------- */
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 的访问)");
}
})();
})();

View File

@@ -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; }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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,
}