import numpy as np
import scipy.optimize


# Profile statistics ####
def gfitoff(x, y, off=None, amp=None, com=None, sigma=None):
    if off is None:
        off = y.min()  # good enough starting point for offset

    if com is None:
        com = x[y.argmax()]

    if amp is None:
        amp = y.max() - off

    # For normalised gauss curve sigma=1/(amp*sqrt(2*pi))
    if sigma is None:
        surface = np.trapz((y-off), x=x)
        sigma = surface / (amp * np.sqrt(2 * np.pi))
    try:
        popt, pcov = scipy.optimize.curve_fit(gauss_fn, x, y, p0=[off, amp, com, sigma], method='lm')        
        popt[3] = abs(popt[3])  # sigma should be returned as positive
        print("Gauss fitting successful.\n")
    except Exception as e:
        print("Gauss fitting not successful.\n" + str(e))
        popt = [off, amp, com, abs(sigma)]

    return popt


def gauss_fn(x, a, b, c, d):
    return a + b * np.exp(-(np.power((x - c), 2) / (2 * np.power(d, 2))))