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

108
web/index.html Normal file
View File

@@ -0,0 +1,108 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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="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>
<header class="site-header">
<div class="wrap">
<div class="brand">
<h1>光纤延时等效采样 · 教学实验</h1>
<span class="badge">仿真演示 · 非实测数据</span>
</div>
<nav>
<a href="#intro">原理</a>
<a href="#demo">动手实验</a>
<a href="#results">结果解读</a>
</nav>
</div>
</header>
<section id="intro" class="wrap">
<div class="card">
<h2>核心命题</h2>
<p>在 ADC 采样率有限的条件下(本项目采样间隔 <strong>10 ns</strong>),能否通过改变光纤长度产生不同的采样相位,重建更密集的荧光衰减曲线,并提高荧光寿命估计的稳定性?</p>
<p>方法:把光信号分成四路,走不同长度的光纤——0 / 9.70 / 19.40 / 29.10 m 产生
0 / 47.5 / 95.0 / 142.5 ns 延时——对 10 ns 采样周期取余得到 0 / 7.5 / 5.0 / 2.5 ns 相位,
按时间排序后即 <strong>0 / 2.5 / 5.0 / 7.5 ns 的等效采样网格</strong>:一把"光学游标卡尺"。</p>
<div class="stats">
<div class="stat"><div class="num">10 ns → 2.5 ns</div><div class="lbl">等效时间细分(离散采样点密度 ×4,不代表模拟带宽提高)</div></div>
<div class="stat"><div class="num">7.65% → 0.60%</div><div class="lbl">原项目 200 次蒙特卡洛:单路 → 四相位 τ̂ 相对标准差</div></div>
<div class="stat"><div class="num">≈52.8 ns</div><div class="lbl">YAG:Ce 荧光标称衰减时间(仿真基准真值)</div></div>
</div>
</div>
</section>
<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>
</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>
</div>
</div>
</section>
<section id="results" class="wrap">
<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>
</ul>
</div>
</section>
<footer>
<div class="wrap">
<p>本页面所有数据均由<strong>软件仿真</strong>生成(Python 计算核心经 Pyodide 在浏览器运行,与论文/CLI 零重写),
不代表任何装置实测结果;2.5 ns 为等效时间细分网格,非整机时间分辨率。</p>
<p>参数与结论来源:2026 全国大学生物理实验竞赛项目《闭环激励下荧光衰减与光纤延时复用相结合的高精度激光功率测量系统》及其教学化后续。</p>
</div>
</footer>
<div id="loading" class="loading-overlay">
<div class="loading-box">
<div class="spinner"></div>
<div id="loadingText">正在加载科学计算运行时(Pyodide + numpy/scipy,首次约 40 MB)…</div>
<div class="loading-sub">加载一次后浏览器会缓存,下次打开很快</div>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>

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 的访问)");
}
})();

116
web/js/style.css Normal file
View File

@@ -0,0 +1,116 @@
/* 光纤延时等效采样教学实验 · 展示网站样式 */
:root {
--primary: #1A5276;
--accent: #2D5F8A;
--warm: #C25B2A;
--bg: #f4f6f8;
--card: #ffffff;
--text: #243342;
--muted: #5d6b7a;
--line: #dde4ea;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.7;
}
.wrap { max-width: 960px; margin: 0 auto; padding: 0 20px; }
/* header */
.site-header {
background: linear-gradient(135deg, #16394f, #2D5F8A);
color: #fff;
padding: 26px 0;
}
.brand { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.brand h1 { font-size: 22px; font-weight: 600; letter-spacing: 0.5px; }
.badge {
background: rgba(255,255,255,.16);
border: 1px solid rgba(255,255,255,.4);
border-radius: 999px;
font-size: 12px; padding: 3px 12px;
}
.site-header nav { margin-left: auto; display: flex; gap: 18px; }
.site-header nav a { color: #cfe0ee; text-decoration: none; font-size: 14px; }
.site-header nav a:hover { color: #fff; }
/* sections */
section { padding: 26px 0 6px; }
.card {
background: var(--card);
border: 1px solid var(--line);
border-radius: 12px;
padding: 26px 28px;
box-shadow: 0 1px 3px rgba(36,51,66,.05);
}
.card h2 { font-size: 18px; color: var(--primary); margin-bottom: 12px; }
.card p { margin-bottom: 10px; }
.hint { color: var(--muted); font-size: 14px; }
/* stats */
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; margin-top: 16px; }
.stat {
background: #f2f6fa; border: 1px solid #dbe6f0; border-radius: 10px;
padding: 14px 16px; text-align: center;
}
.stat .num { font-size: 20px; font-weight: 700; color: var(--accent); white-space: nowrap; }
.stat .lbl { font-size: 12px; color: var(--muted); margin-top: 4px; }
/* controls */
.controls { display: flex; flex-wrap: wrap; gap: 18px 26px; align-items: end; margin: 14px 0 18px; }
.controls label { font-size: 13.5px; display: flex; flex-direction: column; gap: 4px; }
.controls .val { color: var(--warm); font-weight: 600; }
.controls input[type=range] { width: 170px; accent-color: var(--accent); }
.controls select { padding: 5px 8px; border: 1px solid var(--line); border-radius: 6px; background: #fff; }
.controls .chk { flex-direction: row; align-items: center; gap: 6px; }
.btn {
background: var(--primary); color: #fff; border: none; border-radius: 8px;
padding: 9px 18px; font-size: 14px; cursor: pointer;
}
.btn:hover { background: var(--accent); }
.btn:disabled { background: #9aa9b8; cursor: not-allowed; }
/* chart */
.chart { width: 100%; height: 420px; }
/* results */
.results { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; margin-top: 16px; }
.res-item {
background: #f2f6fa; border: 1px solid #dbe6f0; border-radius: 10px;
padding: 12px; text-align: center;
}
.res-num { font-size: 22px; font-weight: 700; color: var(--primary); }
.res-lbl { font-size: 12px; color: var(--muted); }
/* footer */
footer { margin-top: 30px; padding: 22px 0 34px; border-top: 1px solid var(--line); }
footer p { font-size: 12.5px; color: var(--muted); margin-bottom: 6px; }
/* loading */
.loading-overlay {
position: fixed; inset: 0; z-index: 99;
background: rgba(244,246,248,.96);
display: flex; align-items: center; justify-content: center;
transition: opacity .4s;
}
.loading-overlay.hidden { opacity: 0; pointer-events: none; }
.loading-box { text-align: center; max-width: 460px; padding: 20px; }
.spinner {
width: 42px; height: 42px; margin: 0 auto 18px;
border: 4px solid #d5e0ea; border-top-color: var(--accent);
border-radius: 50%; animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.loading-sub { font-size: 12px; color: var(--muted); margin-top: 8px; }
/* mobile */
@media (max-width: 640px) {
.chart { height: 320px; }
.brand h1 { font-size: 18px; }
}

View File

@@ -0,0 +1,9 @@
"""fiber_delay_sim:光纤延时等效采样教学实验仿真软件。
算法核心层(core/)与流程编排(pipeline.py)仅依赖 numpy/scipy,
不依赖文件 IO 与 matplotlib —— 可在本地 CLI 也可经 Pyodide 在浏览器运行
(约束见 docs/实现方案.md §5.1)。
"""
__version__ = "0.1.0"
ALGO_VERSION = "M0+M1"

View File

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

View File

@@ -0,0 +1,101 @@
"""测量链仿真:前端展宽 → 采样 → 噪声 → ADC 量化(仅依赖 numpy)。
物理顺序对应 docs/实现方案.md §7.2。
"""
import numpy as np
def snr_to_sigma(snr_db, peak):
"""峰值定义的信噪比 → 噪声标准差:σ = peak · 10^(−SNR/20)。"""
return float(peak) * 10.0 ** (-float(snr_db) / 20.0)
def gaussian_response(t, y, sigma_ns):
"""模拟前端有限带宽:与高斯冲激响应卷积(sigma_ns<=0 时原样返回)。
sigma_ns 参考值 1.373 ns(原项目 Fisher 分析中的系统响应,报告 5.4.5)。
"""
if sigma_ns is None or sigma_ns <= 0:
return y
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
dt = t[1] - t[0]
half = max(1, int(np.ceil(4.0 * sigma_ns / dt)))
k = (np.arange(2 * half + 1) - half) * dt
kernel = np.exp(-0.5 * (k / sigma_ns) ** 2)
kernel = kernel / kernel.sum()
padded = np.pad(y, half, mode="edge")
return np.convolve(padded, kernel, mode="valid")
def quantize_adc(y, bits, fullscale):
"""理想 ADC 均匀量化:LSB = fullscale / (2^bits − 1)。"""
lsb = float(fullscale) / (2 ** int(bits) - 1)
return np.round(np.asarray(y, dtype=float) / lsb) * lsb
def sample_points(t_cont, y_cont, t0_ns, dt_ns, n_samples):
"""理想采样:t_k = t0 + k·Δt 处线性插值取值。"""
ts = float(t0_ns) + float(dt_ns) * np.arange(int(n_samples))
return ts, np.interp(ts, np.asarray(t_cont, dtype=float), np.asarray(y_cont, dtype=float))
def run_single_channel(t_cont, y_cont, params, rng):
"""单通道测量链(M0)。
params:
dt_ns 采样间隔(默认 10)
t0_ns 触发位置(默认 0)
window_ns 记录窗口(决定采样点数)
snr_db 信噪比(None → 无噪声)
bits ADC 位数(None → 不量化)
fullscale ADC 满量程(None → 2×峰值)
bandwidth_sigma_ns 前端高斯响应宽度(0 → 不展宽)
jitter_ns 时钟抖动标准差(默认 0)
返回 dict(全部纯数据)。
"""
p = dict(params)
t_cont = np.asarray(t_cont, dtype=float)
y_cont = np.asarray(y_cont, dtype=float)
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))
# 1) 前端带宽
y_bw = gaussian_response(t_cont, y_cont, p.get("bandwidth_sigma_ns", 0.0))
# 2) 采样(含可选时钟抖动)
ts = t0 + dt * np.arange(n_samples)
jitter = float(p.get("jitter_ns", 0.0))
if jitter > 0:
ts_eff = ts + rng.normal(0.0, jitter, size=n_samples)
else:
ts_eff = ts
y_clean = np.interp(ts_eff, t_cont, y_bw)
# 3) 噪声(模拟域)
snr_db = p.get("snr_db")
peak = float(np.max(y_bw)) if np.max(y_bw) > 0 else 1.0
sigma = snr_to_sigma(snr_db, peak) if snr_db is not None else 0.0
y_meas = y_clean + (rng.normal(0.0, sigma, size=n_samples) if sigma > 0 else 0.0)
# 4) ADC 量化(数字域)
bits = p.get("bits")
if bits is not None:
fs = p.get("fullscale") or 2.0 * peak
y_meas = quantize_adc(y_meas, bits, fs)
return {
"t_samples": ts,
"y_clean": y_clean,
"y_samples": y_meas,
"sigma": sigma,
"snr_db": snr_db,
"bits": bits,
"n_samples": n_samples,
"jitter_ns": jitter,
"bandwidth_sigma_ns": float(p.get("bandwidth_sigma_ns", 0.0) or 0.0),
}

View File

@@ -0,0 +1,138 @@
"""光纤延时与采样相位设计(仅依赖 numpy,浏览器可运行)。
物理关系(研究报告 2.4 节):
δ = L·n_g/c 传播延时;n_g=1.468 时 1 m ≈ 4.90 ns
φ = δ mod Δt 延时对采样周期取余 → 等效采样相位
δk = k·(S − Δt/N) 原项目设计式:S=50 ns 片段定位间隔,N=4 相位
"""
import itertools
import numpy as np
C_LIGHT = 299_792_458.0 # m/s
N_G_QUARTZ = 1.468 # 石英光纤群折射率(报告 2.4.1)
DT_DEFAULT = 10.0 # ns,高速 ADC 采样间隔
S_LOCATOR_DEFAULT = 50.0 # ns,四段波形片段的定位间隔(报告 2.4.2)
# 原项目名义四组(报告 2.4.2 / 附录 A.4)
NOMINAL_LENGTHS_M = [0.0, 9.70, 19.40, 29.10]
NOMINAL_DELAYS_NS = [0.0, 47.5, 95.0, 142.5] # 精确设计值 δk = k(S−Δt/N)
def delay_from_length(length_m, n_g=N_G_QUARTZ):
"""长度 → 传播延时(ns)。"""
return float(length_m) * n_g / C_LIGHT * 1e9
def length_from_delay(delay_ns, n_g=N_G_QUARTZ):
"""延时(ns)→ 光纤长度(m)。"""
return float(delay_ns) * 1e-9 * C_LIGHT / n_g
def phase_in_period(delay_ns, dt_ns=DT_DEFAULT):
"""延时对采样周期取余 → 等效相位(ns)。"""
return float(delay_ns) % float(dt_ns)
def forward_design(lengths_m=None, delays_ns=None, n_g=N_G_QUARTZ, dt_ns=DT_DEFAULT):
"""正向设计:长度(或设计延时)→ 延时、相位、等效网格与均匀性。
delays_ns 优先(名义延时 47.5/95/142.5 是精确设计值;
名义长度 9.70/19.40/29.10 m 是其四舍五入的反算结果)。
"""
if delays_ns is None:
if lengths_m is None:
raise ValueError("lengths_m 与 delays_ns 至少提供一个")
delays = [delay_from_length(L, n_g) for L in lengths_m]
lengths = [float(L) for L in lengths_m]
else:
delays = [float(d) for d in delays_ns]
lengths = [length_from_delay(d, n_g) for d in delays]
n = len(delays)
phases = [phase_in_period(d, dt_ns) for d in delays]
order = sorted(range(n), key=lambda i: phases[i])
sorted_phases = [phases[i] for i in order]
ideal_step = dt_ns / n if n else 0.0
gaps = [b - a for a, b in itertools.pairwise(sorted_phases)]
if n:
gaps.append(sorted_phases[0] + dt_ns - sorted_phases[-1]) # 循环闭合间隔
gap_dev = [g - ideal_step for g in gaps]
return {
"n_channels": n,
"n_g": n_g,
"dt_ns": float(dt_ns),
"channels": [
{"index": i, "length_m": lengths[i], "delay_ns": delays[i], "phase_ns": phases[i]}
for i in range(n)
],
"phases_ns": phases, # 按通道顺序
"sorted_phases_ns": sorted_phases, # 按时间先后排序 → 等效采样网格
"order_index": order, # 排序后对应的原通道号
"uniformity": {
"ideal_step_ns": ideal_step,
"gaps_ns": gaps,
"max_gap_dev_ns": max((abs(x) for x in gap_dev), default=0.0),
"rms_gap_dev_ns": float(np.sqrt(np.mean(np.square(gap_dev)))) if gap_dev else 0.0,
},
}
def inverse_design(target_phases_ns, dt_ns=DT_DEFAULT, n_g=N_G_QUARTZ,
s_locator_ns=S_LOCATOR_DEFAULT, max_m=15):
"""反向设计:目标相位 → 候选延时/长度与推荐解。
- 目标为均匀网格 j·Δt/N 时,给出构造式推荐解 δk = k·(S − Δt/N)
(复现原项目方案:0/2.5/5/7.5 ns → 0/142.5/95/47.5 ns → 0/29.10/19.40/9.70 m);
- 目标非均匀时,返回每相位候选表并提示网格不均匀(这本身是教学点)。
"""
targets = sorted({round(float(p) % float(dt_ns), 12) for p in target_phases_ns})
n = len(targets)
tol = 1e-9 * max(1.0, float(dt_ns))
ideal_grid = [float(dt_ns) * j / n for j in range(n)]
is_uniform = all(abs(tg - idl) <= tol for tg, idl in zip(targets, ideal_grid))
result = {
"n_channels": n,
"dt_ns": float(dt_ns),
"n_g": n_g,
"target_phases_ns": targets,
"is_uniform_grid": is_uniform,
"candidates": [], # 每相位候选:[{phase_ns, m, delay_ns, length_m}]
"recommended": None, # 均匀网格时的构造式推荐
"construction": None,
}
for ph in targets:
cand = []
for m in range(int(max_m) + 1):
delay = ph + m * float(dt_ns)
cand.append({
"phase_ns": ph, "m": m,
"delay_ns": delay,
"length_m": length_from_delay(delay, n_g),
})
result["candidates"].append(cand)
if is_uniform and n >= 2:
step = float(s_locator_ns) - float(dt_ns) / n
rec = []
for j, ph in enumerate(targets):
k = (n - j) % n # j=0(φ=0)→k=0;j=1→k=n-1;… 复现原项目逐级递推
delay = k * step
rec.append({
"phase_ns": ph, "k": k, "delay_ns": delay,
"length_m": length_from_delay(delay, n_g),
})
# 校验:推荐延时反算相位应等于目标相位
for entry in rec:
assert abs(phase_in_period(entry["delay_ns"], dt_ns) - entry["phase_ns"]) < 1e-6
result["recommended"] = rec
result["construction"] = (
f"δk = k·(S − Δt/N),S={float(s_locator_ns):g} ns,Δt/N={float(dt_ns)/n:g} ns"
)
return result

View File

@@ -0,0 +1,145 @@
"""寿命拟合:非线性最小二乘(单/双指数)、对数线性、稳健拟合(仅依赖 numpy/scipy.optimize)。
算法对比设计见 docs/实现方案.md §7.5:
- 对数线性需先扣基线,对数变换使低信噪比尾部噪声权重失真(教学点);
- NLS 为基准算法:理想无噪数据应零偏差复现设定寿命(对应原项目"标准拟合"验证)。
"""
import numpy as np
from scipy.optimize import curve_fit, least_squares
def _single_exp(t, A, tau, B):
return A * np.exp(-t / tau) + B
def _double_exp(t, A1, tau1, A2, tau2, B):
return A1 * np.exp(-t / tau1) + A2 * np.exp(-t / tau2) + B
def initial_guess_single(t, y):
"""单指数自动初值:尾段均值作基线、首点定幅度、半衰点定 tau。"""
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
tail_n = max(1, len(y) // 5)
B0 = float(np.mean(y[-tail_n:]))
A0 = float(y[0] - B0)
if A0 <= 0:
A0 = max(float(np.max(y) - B0), 1e-9)
half = B0 + A0 / 2.0
below = np.where(y <= half)[0]
t_half = float(t[below[0]]) if len(below) else float(t[len(t) // 2])
tau0 = max(t_half / np.log(2.0), 1e-3)
return [A0, tau0, B0]
def fit_single_exp_nls(t, y, p0=None):
"""单指数 + 常数基线的非线性最小二乘拟合。"""
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
if p0 is None:
p0 = initial_guess_single(t, y)
popt, pcov = curve_fit(
_single_exp, t, y, p0=p0,
bounds=([0.0, 1e-9, -np.inf], [np.inf, np.inf, np.inf]),
maxfev=50000,
)
resid = y - _single_exp(t, *popt)
perr = np.sqrt(np.abs(np.diag(pcov)))
return {
"model": "single_exp_baseline",
"A": float(popt[0]), "tau": float(popt[1]), "B": float(popt[2]),
"A_err": float(perr[0]), "tau_err": float(perr[1]), "B_err": float(perr[2]),
"rmse": float(np.sqrt(np.mean(resid ** 2))),
"residual": resid,
"popt": [float(v) for v in popt],
}
def fit_log_linear(t, y, tail_frac=0.2, b=None):
"""对数线性拟合:ln(I−B) 对 t 线性回归 → tau = −1/slope。
b=None 时用尾段均值估计基线(注意:对 B=0 的纯信号,尾段估计本身
就引入偏差——这正是"基线估计误差"教学点,见 docs/实现方案.md §7.5);
b 已知时直接使用(此时对数线性与 NLS 在理想数据上数学等价)。
返回剔除的非正点数(对数前需 I−B>0),供教学观察。
"""
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
if b is None:
tail_n = max(1, int(len(y) * tail_frac))
B = float(np.mean(y[-tail_n:]))
baseline_estimated = True
else:
B = float(b)
baseline_estimated = False
yy = y - B
mask = yy > 0
dropped = int(np.sum(~mask))
if mask.sum() < 2:
return {"model": "log_linear", "tau": None, "A": None, "B_est": B,
"baseline_estimated": baseline_estimated,
"dropped_points": dropped, "n_used": int(mask.sum())}
slope, intercept = np.polyfit(t[mask], np.log(yy[mask]), 1)
tau = -1.0 / slope if slope < 0 else None
return {
"model": "log_linear",
"tau": float(tau) if tau else None,
"A": float(np.exp(intercept)),
"B_est": B,
"baseline_estimated": baseline_estimated,
"dropped_points": dropped,
"n_used": int(mask.sum()),
}
def fit_double_exp_nls(t, y, p0=None):
"""双指数 + 常数基线 NLS(M4 复现蒙特卡洛用)。
初值策略:先单指数拟合,快成分取 0.2·A、0.1·tau。
"""
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
if p0 is None:
s = fit_single_exp_nls(t, y)
p0 = [0.2 * s["A"], max(0.1 * s["tau"], 1e-3), 0.8 * s["A"], s["tau"], s["B"]]
popt, pcov = curve_fit(
_double_exp, t, y, p0=p0,
bounds=([0, 1e-6, 0, 1e-6, -np.inf], [np.inf, np.inf, np.inf, np.inf, np.inf]),
maxfev=100000,
)
resid = y - _double_exp(t, *popt)
perr = np.sqrt(np.abs(np.diag(pcov)))
return {
"model": "double_exp_baseline",
"A1": float(popt[0]), "tau1": float(popt[1]),
"A2": float(popt[2]), "tau2": float(popt[3]), "B": float(popt[4]),
"tau1_err": float(perr[1]), "tau2_err": float(perr[3]),
"rmse": float(np.sqrt(np.mean(resid ** 2))),
"residual": resid,
"popt": [float(v) for v in popt],
}
def fit_single_exp_robust(t, y, loss="soft_l1", f_scale=None):
"""稳健拟合(扩展功能):least_squares + huber/soft_l1 损失。"""
t = np.asarray(t, dtype=float)
y = np.asarray(y, dtype=float)
p0 = initial_guess_single(t, y)
if f_scale is None:
f_scale = max(float(np.std(np.diff(y))) * 2.0, 1e-9)
def resid_fn(p):
A, tau, B = p
return A * np.exp(-t / tau) + B - y
res = least_squares(
resid_fn, p0, bounds=([0.0, 1e-9, -np.inf], [np.inf, np.inf, np.inf]),
loss=loss, f_scale=f_scale, max_nfev=50000,
)
return {
"model": f"single_exp_robust_{loss}",
"A": float(res.x[0]), "tau": float(res.x[1]), "B": float(res.x[2]),
"rmse": float(np.sqrt(np.mean(res.fun ** 2))),
"success": bool(res.success),
}

View File

@@ -0,0 +1,49 @@
"""荧光衰减信号模型与真值预设(仅依赖 numpy,浏览器可运行)。
三套预设的来源与区别见 docs/项目说明.md §3.2 / §6:
- "monte_carlo" 报告 5.4.4 蒙特卡洛仿真真值(快成分 0.60 ns 为仿真设定值)
- "single" 单指数教学版(YAG:Ce 标称衰减 52.8 ns)
- "measured_ref" 实测参考(附图 A1 标注寿命;权重原始材料未给出,沿用 0.16/0.84 为假设值)
"""
import numpy as np
PRESETS = {
"monte_carlo": {"A1": 0.16, "tau1": 0.60, "A2": 0.84, "tau2": 52.80, "B0": 0.0, "B1": 0.0},
"single": {"A1": 0.0, "tau1": None, "A2": 1.0, "tau2": 52.8, "B0": 0.0, "B1": 0.0},
"measured_ref": {"A1": 0.16, "tau1": 5.0, "A2": 0.84, "tau2": 52.5, "B0": 0.0, "B1": 0.0},
}
def resolve_preset(preset, tau=None, amplitude=1.0, b0=0.0, b1=0.0):
"""按预设名取参数;允许覆盖 tau/幅度/基线(单指数预设)。"""
if preset not in PRESETS:
raise ValueError(f"未知预设 {preset!r},可选:{list(PRESETS)}")
p = dict(PRESETS[preset])
if preset == "single":
if tau is not None:
p["tau2"] = float(tau)
p["A2"] = float(amplitude)
if b0:
p["B0"] = float(b0)
if b1:
p["B1"] = float(b1)
return p
def generate(t, params):
"""荧光衰减信号 I(t) = A1·exp(-t/tau1) + A2·exp(-t/tau2) + B0 + B1·t。
tau 为 None 或幅度为 0 时对应项不参与(单指数退化)。
"""
t = np.asarray(t, dtype=float)
y = np.full(t.shape, float(params.get("B0", 0.0))) + float(params.get("B1", 0.0)) * t
a1 = float(params.get("A1", 0.0))
tau1 = params.get("tau1")
if a1 != 0.0 and tau1:
y = y + a1 * np.exp(-t / float(tau1))
a2 = float(params.get("A2", 0.0))
tau2 = params.get("tau2")
if a2 != 0.0 and tau2:
y = y + a2 * np.exp(-t / float(tau2))
return y

View File

@@ -0,0 +1,101 @@
"""实验流程编排:参数 → 生成 → 采样 → 拟合 → 结果(纯数据,Pyodide 可运行)。
M0:单指数信号 + 10 ns 直接采样 + 噪声 + NLS 寿命拟合。
"""
import numpy as np
from .core import acquisition, fitting, signal
from . import ALGO_VERSION
M0_DEFAULTS = {
"preset": "single", # single / monte_carlo / measured_ref
"tau": 52.8, # ns(仅 single 预设生效)
"amplitude": 1.0,
"b0": 0.0,
"b1": 0.0,
"window_ns": 400.0,
"dt_ns": 10.0,
"t0_ns": 0.0,
"snr_db": 50.0, # None → 无噪声
"bits": 12, # None → 不量化
"bandwidth_sigma_ns": 0.0,
"jitter_ns": 0.0,
}
CONT_STEP_NS = 0.01 # 连续曲线网格步长(仅用于画图与插值)
def _resolve(params):
"""合并默认参数并解析为信号/采集两组参数。"""
p = dict(M0_DEFAULTS)
p.update({k: v for k, v in (params or {}).items() if v is not None or k in ("snr_db", "bits", "b0", "b1")})
sig_params = signal.resolve_preset(p["preset"], tau=p["tau"], amplitude=p["amplitude"],
b0=p["b0"], b1=p["b1"])
return p, sig_params
def run_m0(params=None, seed=42):
"""单次 M0 实验:生成 → 采样 → 拟合。返回纯数据 dict。"""
p, sig_params = _resolve(params)
rng = np.random.default_rng(seed)
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_params = {
"dt_ns": p["dt_ns"], "t0_ns": p["t0_ns"], "window_ns": p["window_ns"],
"snr_db": p.get("snr_db"), "bits": p.get("bits"),
"bandwidth_sigma_ns": p["bandwidth_sigma_ns"], "jitter_ns": p["jitter_ns"],
}
acq = acquisition.run_single_channel(t_cont, y_cont, acq_params, rng)
fit = fitting.fit_single_exp_nls(acq["t_samples"], acq["y_samples"])
tau_true = float(sig_params["tau2"])
rel_err = abs(fit["tau"] - tau_true) / tau_true if tau_true else None
return {
"meta": {
"experiment": "m0_single_channel_fit",
"algo_version": ALGO_VERSION,
"data_origin": "software-simulated",
"seed": int(seed),
"params": {k: (v if not isinstance(v, float) else round(v, 6)) for k, v in p.items()},
},
"t_cont": t_cont, "y_cont": y_cont,
"t_samples": acq["t_samples"], "y_clean": acq["y_clean"], "y_samples": acq["y_samples"],
"n_samples": acq["n_samples"], "sigma": acq["sigma"],
"snr_db": acq["snr_db"], "bits": acq["bits"],
"fit": {k: v for k, v in fit.items() if k != "residual"},
"residual": fit["residual"],
"tau_hat": fit["tau"], "tau_true": tau_true, "rel_error": rel_err,
}
def run_m0_repeats(params=None, repeats=20, seed=0):
"""重复 M0 实验(不同种子)→ τ̂ 分布统计。"""
p, sig_params = _resolve(params)
tau_true = float(sig_params["tau2"])
tau_hats, n_pts = [], []
for i in range(int(repeats)):
rec = run_m0(params, seed=seed + i)
tau_hats.append(rec["tau_hat"])
n_pts.append(rec["n_samples"])
arr = np.asarray(tau_hats, dtype=float)
mean = float(np.mean(arr))
return {
"meta": {
"experiment": "m0_repeats",
"algo_version": ALGO_VERSION,
"data_origin": "software-simulated",
"base_seed": int(seed), "repeats": int(repeats),
"params": {k: v for k, v in p.items()},
},
"tau_true": tau_true,
"tau_hats": tau_hats,
"n_samples": int(n_pts[0]) if n_pts else 0,
"mean": mean,
"std": float(np.std(arr, ddof=1)) if len(arr) > 1 else 0.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,
}