I am trying to create a Gaussian Fit by using scipy.opimize curve fit. My y datas have a poisson error, so i need to integrate this uncertainties into my curve fit, but I don't know how.
At first a create a function fit_gauss which worked without the error in y. Now i try to modifize this code. That's what i got:
x = x_data #datas are imported from file
y = y_data
y_un = unp.uarray(y, np.sqrt(y))
print("DATA - Gauss")
#Define Gauss function
def f_gauss(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
#Define Fitting function
def fit_gauss(x,y,title,path):
n=len(x)
mean=sum(x*y)/n
w=[0]*len(x)
for i in range(len(x)):
w[i]=y[i]*(x[i]-mean)**2
sigma = (sum(w) / sum(y))**(1 / 2)
#sigma = (sum(y * (x - mean)**2) / sum(y))**(1/2)
gopt, gcov = curve_fit(
f_gauss,
x, y,
p0=[max(y),mean,sigma]
) #trying to use curve fit
gerrors = np.sqrt(np.diag(gcov))
unparams_gauss = unp.uarray(gopt, gerrors)
print(f"""
{title}
Mean: {mean}
Sigma: {sigma}
a={unparams_gauss[0]}
x0={unparams_gauss[1]}
sigma={unparams_gauss[2]}
""")
#plotting
plt.title(title)
plt.plot(x, y, "k", label=f"{title}")
plt.plot(x, f_gauss(x, *gopt), "r--", label="Gauß Fit")
plt.legend(loc="best")
plt.savefig(path)
plt.close()
fit_gauss(x,y_un,"Cs-137","plots/gauss_fit.pdf")