I am struggling right now with Lorentzian curve fit. I'll try to explain my problem. I need to write my own code for Lorentzian curve fit so I can add some stuff to the equations. I've implemented Lorentzian fit with model
and def
, I've written similary, but it doesn't work. Check out my code:
So here are my data:
for dataset in [Bxfft]:
dataset = np.asarray(dataset)
freqs, psd = signal.welch(dataset, fs=266336/300, window='hamming', nperseg=16192, scaling='density')
plt.semilogy(freqs[30:-7000], psd[30:-7000]/dataset.size**0, color='r', label='Bx')
x = freqs[100:-7900]
y = psd[100:-7900]
Here is Lorentzian curve fit defined by me:
def lorentzian(x, amp, cen, sig):
return (amp/np.pi) * (sig/(x-cen)**2 + sig**2)
model = Model(lorentzian)
pars = model.make_params(amp=6, cen=5, sig=1)
pars['amp'].max = 6
result = model.fit(y, pars, x=x)
final_fit = result.best_fit
print(result.fit_report(min_correl=0.25))
plt.plot(x, final_fit, 'k--', linewidth=3)
And here done by model function:
model2 = LorentzianModel()
params2 = model2.make_params(amplitude=6, center=5, sigma=1)
params2['amplitude'].value = 6
result2 = model2.fit(y, params2, x=x)
final_fit2 = result2.best_fit
print(result2.fit_report(min_correl=0.25))
plt.plot(x, final_fit2, 'k--', linewidth=3)
The upper plot goes for def
Lorentzian, and the lower plot goes for model
Lorentzian.