Search code examples
scipyleast-squareschi-squared

scipy.optimize.leastsq : How to specify non-parameters?


I want to know how to use leastsq from scipy for chi-square fitting. I know the structure is basically -

parameters = leastsq(chi(exp_data, exp_err, param), initial_guess, arg = (?,?,?))

where exp_data, exp_err are arrays

def fitted_data(param):
    fitted_data = a*param[0] + b*param[1]**2 + c*np.sin(param[3])

return fitted_data

def chi(exp_data, exp_err, param):
    chi = (exp_data - fitted_data(param))/exp_err

return(chi)

What I don't understand is how to specify only param as the parameters to explore for chi square fitting. I don't understand how to use arg = (?,?,?), as I have multiple inputs for the function chi, not just parameters.

Thank you very much.


Solution

  • leastsq takes a function to be minimized. This function has to be dependent on the parameters of your fit, and may additionally be dependent on other parameters, that are considered constant for the minimization. These are provided via the args-argument as a tuple. The parameters are to be provided as the first argument, and all additional arguments may follow after. Your function to be minimized therefor needs to look like this:

    def residuals(params, args)
    

    I adjusted your code to fit these requirements:

    def fitted_data(params) :
        fitted_data = a*params[0] + b*params[1]**2 + c*np.sin(params[3])
    return fitted_data
    
    def chi(params, exp_data, exp_err) :
        chi = (exp_data - fitted_data(params)/exp_err
    return chi
    
    result = scipy.optimize.leastsq(chi, x0=(1, 1, 1), args=(exp_data, exp_err))