Search code examples
pythonmodelscipycurve-fittinglmfit

curve fitting with lmfit python


I am new to python and trying to fit data using lmfit. I am following on the lmfit tutorial here: http://lmfit.github.io/lmfit-py/parameters.html and this is my code (based on the code explained in the above link):

import numpy as np
import lmfit 
import matplotlib.pyplot as plt
from numpy import exp, sqrt, pi
from lmfit import minimize,Parameters,Parameter,report_fit

data=np.genfromtxt('test.txt',delimiter=',')

x=data[:,][:,0]
y=data[:,][:,1]

def fcn2fit(params,x,y):
    """model decaying sine wave, subtract data"""
    S1=params['S1'].value
    t0=params['t0'].value
    T1=params['T1'].value
    S2=params['S2'].value
    T2=params['T2'].value

    model = 1-(1-S1)*exp(-(x-t0)/T1)+S2*(1-exp(-(x-t0)/T2)
    return model - y  

params = Parameters()
params.add('S1', value=0.85, min=0.8, max=0.9)
params.add('t0', value=0.05, min=0.01, max=0.1)
params.add('T1', value=0.2, min=0.1, max=0.3)
params.add('S2', value=0.03, min=0.01, max=0.05)
params.add('T2', value=0.3, min=0.2, max=0.4)

result = minimize(fcn2fit, params, args=(x,y))
final = y + result.residual

report_fit (params)

try:
    import pylab
    pylab.plot(x,y, 'k+')
    pylab.plot(x,final, 'r')
    pylab.show()
except:
    pass

Problem: it return syntax error for line return model-y

I appreciate if you could please let me to right direction.


Solution

  • I think there is a parenthesis problem in the previous line. This causes the return to be included in the formula. I think there's a ) missing at the end.