update at 2026-10-12 15:14:13

This commit is contained in:
douboer
2026-10-12 15:14:13 +08:00
parent 7a225ff2b1
commit db63516781
12 changed files with 1012 additions and 43 deletions

196
web/js/app.js Normal file
View File

@@ -0,0 +1,196 @@
/* app.js:Pyodide 加载同一 core/ 算法核心 → ECharts 渲染 M0 交互演示 */
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/pipeline.py",
];
// 浏览器侧包装函数:调用 pipeline.run_m0,输出轻量 JSON(连续曲线降采样)
const PY_WRAPPER = `
import json
import numpy as np
from fiber_delay_sim import pipeline
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) # 连续曲线降采样至 ~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"],
})
`;
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; }
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 可导入
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.runPython(PY_WRAPPER);
pyRunM0 = pyodide.globals.get("run_m0_web");
$("loading").classList.add("hidden");
}
function readParams() {
return {
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 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" } },
},
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,
},
],
};
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) + "%";
$("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(); }
}
}
function bindControls() {
const refresh = () => run();
let timer = null;
const debounced = () => { clearTimeout(timer); timer = setTimeout(refresh, 250); };
$("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();
});
chart = echarts.init($("chart"));
window.addEventListener("resize", () => chart && chart.resize());
}
(async function main() {
bindControls();
try {
await initPyodide();
await run();
} catch (e) {
console.error(e);
setLoading("加载失败:" + e.message + "(请刷新重试,或检查网络对 cdn.jsdelivr.net 的访问)");
}
})();