update at 2026-10-12 16:25:51
This commit is contained in:
@@ -5,5 +5,5 @@
|
||||
(约束见 docs/实现方案.md §5.1)。
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
ALGO_VERSION = "M0+M1"
|
||||
__version__ = "0.5.0"
|
||||
ALGO_VERSION = "M0-M4"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""算法核心层:signal / fiber / acquisition / fitting(全部 Pyodide 兼容)。"""
|
||||
"""算法核心层:signal / fiber / acquisition / calibration / fitting / statistics(全部 Pyodide 兼容)。"""
|
||||
|
||||
from . import signal, fiber, acquisition, fitting
|
||||
from . import signal, fiber, acquisition, calibration, fitting, statistics
|
||||
|
||||
__all__ = ["signal", "fiber", "acquisition", "fitting"]
|
||||
__all__ = ["signal", "fiber", "acquisition", "calibration", "fitting", "statistics"]
|
||||
@@ -99,3 +99,81 @@ def run_single_channel(t_cont, y_cont, params, rng):
|
||||
"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
web/py/fiber_delay_sim/core/calibration.py
Normal file
154
web/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))),
|
||||
}
|
||||
88
web/py/fiber_delay_sim/core/statistics.py
Normal file
88
web/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}
|
||||
@@ -1,11 +1,14 @@
|
||||
"""实验流程编排:参数 → 生成 → 采样 → 拟合 → 结果(纯数据,Pyodide 可运行)。
|
||||
"""实验流程编排:参数 → 生成 → 采样 → 校准 → 拟合 → 统计(纯数据,Pyodide 可运行)。
|
||||
|
||||
M0:单指数信号 + 10 ns 直接采样 + 噪声 + NLS 寿命拟合。
|
||||
里程碑映射:
|
||||
- M0:单指数信号 + 10 ns 直接采样 + 噪声 + NLS 寿命拟合;
|
||||
- M2:四通道光纤延时采样 + 通道误差注入 + 校准(名义 vs 标定)对比;
|
||||
- M4:单通道直接采样 vs 四相位等效采样 的双指数 τ₂ 蒙特卡洛对比。
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import acquisition, fitting, signal
|
||||
from .core import acquisition, calibration, fitting, signal, statistics
|
||||
from . import ALGO_VERSION
|
||||
|
||||
M0_DEFAULTS = {
|
||||
@@ -99,3 +102,145 @@ def run_m0_repeats(params=None, repeats=20, seed=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