aminnj / yahist

1D and 2D histogram objects
10 stars 2 forks source link

Hist1D fit method is incorrect #16

Open hswanson13 opened 1 week ago

hswanson13 commented 1 week ago

Sorry for the really short and poor issue, but I believe I have found a bug in the yahist fitting. If you perform the fit like:

what = dt_yahist.fit("gaus", color="green")
#these numbers are incorrect...
mean = what['params']['mean']['value']
sigma = what['params']['sigma']['value']
N = what['params']['constant']['value']

This does not match with a manually fitting like this (sorry for giving the whole overwritten Hist1D class I used to do a rough fix of the fitting):

class Hist1D(Hist1D):
    def __init__(self, *args, **kwargs):
        super(Hist1D, self).__init__(*args, **kwargs)

    def fit(self, fit_method: str, color: str='red'):
        yax = plt.gca()
        if fit_method == 'gaus':
            gaus = lambda x, N, mu, sigma: N*np.exp(-(x-mu)**2/(2.0*sigma**2))
        else:
            raise NotImplementedError("Hey sorry this fit method is not implemented, you can add it though :)")

        peak_center = self.bin_centers[self.counts == np.max(self.counts)][0]
        amplitude = np.max(self.counts)

        coeff, _ = curve_fit(gaus, self.bin_centers, self.counts, p0=[amplitude, peak_center, 0.1])
        yax.plot(
            self.bin_centers,
            gaus(self.bin_centers, *coeff),
            color="red",
            linewidth=2,
            label='Gaussian Fit\n mean: {:.3f} \n sigma: {:.4f}'.format(coeff[1],abs(coeff[2])),
        )

What alerted us something was wrong:

image

hswanson13 commented 1 week ago

You can also see another plot:

again blue is the manual fit and red here is the yahist fit image