/* app.js:Pyodide 加载同一 core/ 算法核心 → ECharts 渲染五个里程碑交互页 */ const CORE_FILES = [ "fiber_delay_sim/__init__.py", "fiber_delay_sim/core/__init__.py", "fiber_delay_sim/core/signal.py", "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", ]; 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)} rec = pipeline.run_m0(params, seed=int(seed)) 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"], "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 seed = 42; let pyodideReady = null; // 初始化完成的 Promise(供 callPy 统一等待) 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, '/')"); for (const rel of CORE_FILES) { const res = await fetch("py/" + rel); if (!res.ok) throw new Error(`加载 ${rel} 失败:HTTP ${res.status}`); const code = await res.text(); const dir = rel.split("/").slice(0, -1).join("/"); pyodide.runPython(`import os; os.makedirs("/${dir}", exist_ok=True)`); pyodide.FS.writeFile("/" + rel, code); } // 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"); } /* 等待 Pyodide 完全就绪(含 numpy/scipy 与 wrapper 注册);重复调用共享同一个 Promise */ function waitPyodide() { if (!pyodideReady) { pyodideReady = initPyodide().catch((e) => { pyodideReady = null; // 失败后允许下次重试 throw e; }); } return pyodideReady; } async function callPy(name, args) { await waitPyodide(); let fn = pyodide.globals.get(name); if (fn === undefined) { // 防御:首次注册可能受 Pyodide 文件导入时序影响,重新执行一次 wrapper console.warn("注册函数缺失,重新执行 wrapper:", name); pyodide.runPython("import importlib; importlib.invalidate_caches()"); pyodide.runPython(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), }; 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); getChart("chartM0").setOption({ ...baseLineOption(), legend: { top: 8, data: ["连续信号(真值)", "10 ns 采样点", "NLS 拟合"] }, series: [ { 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", data: out.t_samples.map((t, i) => [t, out.y_samples[i]]), 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 }, ], }, 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; } /* ================= 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: 54 }, tooltip: {}, xAxis: { type: "value", name: "延时 (ns)", nameLocation: "middle", nameGap: 34, 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) + (out.ll.B_est || 0)) : []; 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; const Bv = typeof r.B_est === "number" ? r.B_est : (typeof r.B === "number" ? r.B : null); const Btxt = Bv == null ? "—" : Bv.toFixed(4); return `${name}${r.tau.toFixed(3)}${err.toFixed(2)}%${Btxt}`; }; $("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() { let timer = null; const debounce = (fn, ms = 250) => { clearTimeout(timer); timer = setTimeout(fn, ms); }; $("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(); }); $("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 waitPyodide(); // 仅渲染当前可见的 M0 tab;其余 tab 首次切换时惰性渲染(避免隐藏容器尺寸为 0) tabRan["tab-m0"] = true; await runM0(); } catch (e) { console.error(e); setLoading("加载失败:" + e.message + "(请刷新重试,或检查网络对 cdn.jsdelivr.net 的访问)"); } })();