[Python] Cosine with a Gaussian envelope fit failing in python using scipy.optimize.curve_fit

Discussão em 'Python' iniciado por Stack, Maio 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to fit data that resembles a cosine function with a decaying Gaussian envelope using python, and in particular scipy.optimize.curve_fit. However, it seems like my code is not varying the parameters enough.

    For example, in this data, the center of the interferogram is slightly negative (around -0.1), but even when I provide a guess that is very close, the optimized parameters are clearly off. The horizontal offset just stays very close to my initial guess even if it is clearly not an optimal point. I checked that by manually varying the horizontal offset and calculating the coefficient of determination and the values offered by curve_fit are not the most optimal.

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    from scipy.optimize import curve_fit

    id_ = '0'

    filename = '250516_FF_01_coincidences_'+id_+'mm.txt'


    def FF_function(x,l,s,A,xoff):
    d = x - xoff
    return A*np.cos(2*np.pi/l*d)*np.exp(-0.5*(d/s)**2)+A #

    data = pd.read_csv(filename, sep=' ',header= None).to_numpy()

    # data = data.astype(dtype=np.float32)

    fig = plt.subplots(figsize=(10,5))
    ax = plt.subplot(111)

    ax.plot(data[:,0],data[:,1],alpha = 0.3)

    guess = [4.40673558e-02, 2.63973377e-01, 1.63702697e+02, -0.2]

    xx=np.linspace(min(data[:,0]),max(data[:,0]),1000)
    # ax.plot(xx,FF_function(xx,*guess)

    popt,cov = curve_fit(FF_function,data[:,0],data[:,1],p0 = guess)
    ax.plot(xx,FF_function(xx,*popt), color ='C0',alpha = 0.5)

    SSE = np.sum(np.square(data[:,1]-FF_function(data[:,0], *popt)))
    SST = np.sum(np.square(data[:,1]-np.mean(data[:,1])))
    r2 = 1 - SSE/SST
    print(r2)


    print(popt)

    #
    ax.set_xlabel('Displacement (mm)')
    ax.set_ylabel('Coincidences')


    Example

    I can try doing a manual minimization of the determination coefficient, but I'm curious about what is going wrong in my fit.

    Continue reading...

Compartilhe esta Página