Files
2026-10-12 14:26:51 +08:00

146 lines
5.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""寿命拟合:非线性最小二乘(单/双指数)、对数线性、稳健拟合(仅依赖 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),
}