在一组数据中拟合多个独立和重叠的洛伦兹峰,可以使用非线性最小二乘拟合方法
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def lorentzian(x, A, x0, gamma):
return A * (1 / (1 + ((x - x0) / gamma) ** 2))
# 示例数据
x = np.linspace(-10, 10, 1000)
y = 3 * lorentzian(x, 1, -2, 0.5) + 2 * lorentzian(x, 1, 0, 0.5) + 1 * lorentzian(x, 1, 2, 0.5) + 0.1 * np.random.normal(0, 1, len(x))
def multi_lorentzian(x, params):
n_peaks = len(params) // 3
y_fit = np.zeros_like(x)
for i in range(n_peaks):
A, x0, gamma = params[i * 3:i * 3 + 3]
y_fit += lorentzian(x, A, x0, gamma)
return y_fit
# 假设有3个洛伦兹峰
n_peaks = 3
params_init = np.random.rand(n_peaks * 3)
curve_fit
进行拟合:params_opt, cov_matrix = curve_fit(multi_lorentzian, x, y, p0=params_init)
y_fit = multi_lorentzian(x, params_opt)
plt.plot(x, y, 'ko', label='Data')
plt.plot(x, y_fit, 'r-', label='Fit')
plt.legend()
plt.show()
领取专属 10元无门槛券
手把手带您无忧上云