update at 2026-10-12 18:55:48
This commit is contained in:
9
figma/public/py/fiber_delay_sim/__init__.py
Normal file
9
figma/public/py/fiber_delay_sim/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
"""fiber_delay_sim:光纤延时等效采样教学实验仿真软件。
|
||||
|
||||
算法核心层(core/)与流程编排(pipeline.py)仅依赖 numpy/scipy,
|
||||
不依赖文件 IO 与 matplotlib —— 可在本地 CLI 也可经 Pyodide 在浏览器运行
|
||||
(约束见 docs/实现方案.md §5.1)。
|
||||
"""
|
||||
|
||||
__version__ = "0.5.0"
|
||||
ALGO_VERSION = "M0-M4"
|
||||
5
figma/public/py/fiber_delay_sim/core/__init__.py
Normal file
5
figma/public/py/fiber_delay_sim/core/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""算法核心层:signal / fiber / acquisition / calibration / fitting / statistics(全部 Pyodide 兼容)。"""
|
||||
|
||||
from . import signal, fiber, acquisition, calibration, fitting, statistics
|
||||
|
||||
__all__ = ["signal", "fiber", "acquisition", "calibration", "fitting", "statistics"]
|
||||
179
figma/public/py/fiber_delay_sim/core/acquisition.py
Normal file
179
figma/public/py/fiber_delay_sim/core/acquisition.py
Normal file
@@ -0,0 +1,179 @@
|
||||
"""测量链仿真:前端展宽 → 采样 → 噪声 → 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),
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
}
|
||||
154
figma/public/py/fiber_delay_sim/core/calibration.py
Normal file
154
figma/public/py/fiber_delay_sim/core/calibration.py
Normal 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))),
|
||||
}
|
||||
138
figma/public/py/fiber_delay_sim/core/fiber.py
Normal file
138
figma/public/py/fiber_delay_sim/core/fiber.py
Normal 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
|
||||
145
figma/public/py/fiber_delay_sim/core/fitting.py
Normal file
145
figma/public/py/fiber_delay_sim/core/fitting.py
Normal 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),
|
||||
}
|
||||
49
figma/public/py/fiber_delay_sim/core/signal.py
Normal file
49
figma/public/py/fiber_delay_sim/core/signal.py
Normal 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
|
||||
88
figma/public/py/fiber_delay_sim/core/statistics.py
Normal file
88
figma/public/py/fiber_delay_sim/core/statistics.py
Normal 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}
|
||||
246
figma/public/py/fiber_delay_sim/pipeline.py
Normal file
246
figma/public/py/fiber_delay_sim/pipeline.py
Normal file
@@ -0,0 +1,246 @@
|
||||
"""实验流程编排:参数 → 生成 → 采样 → 校准 → 拟合 → 统计(纯数据,Pyodide 可运行)。
|
||||
|
||||
里程碑映射:
|
||||
- M0:单指数信号 + 10 ns 直接采样 + 噪声 + NLS 寿命拟合;
|
||||
- M2:四通道光纤延时采样 + 通道误差注入 + 校准(名义 vs 标定)对比;
|
||||
- M4:单通道直接采样 vs 四相位等效采样 的双指数 τ₂ 蒙特卡洛对比。
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import acquisition, calibration, fitting, signal, statistics
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
# ---------- 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,
|
||||
}
|
||||
Reference in New Issue
Block a user