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

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