Fitting Multiple Data Sets Using Scipy.optimize With The Same Parameters
I am trying to write a code that would fit multiple (>100) data sets with the same parameters. For a simple example: Suppose I have 4 different data sets that are supposed to a
Solution 1:
I have actually figured it out in the last couple of days. I'll provide the code in case it may be of interest to anyone. I also found that fitting sine functions is pretty hard, so I changed my fake data to Lorentzians.
Importing modules and generating fake data, that will be kept in the the lists of lists:
from scipy import optimize
import matplotlib
from matplotlib import pyplot as plt
from scipy import *
import numpy as np
Mat_ydata=[]
Mat_angle=[]
Mat_xdata=[]
for c inrange(0,100,20):
num_points=c+100
xdata=linspace(0,num_points/2, num_points)
ydata=5.1/((xdata-c)**2+2.1**2)+0.05*((0.5rand(num_points))*exp(2*rand(num_points)**2))
Mat_angle.append(c)
Mat_ydata.append(ydata)
Mat_xdata.append(xdata)
Defining the fitting function and the error function:
deflor_func(x,c,par):
a,b,d=par
return a/((x-c)**2+b**2)
deferr (p,c,x,y):
return lor_func(x,c,p)-y
deferr_global(p,Mat_a,Mat_x,Mat_y):
err0=[]
for i inrange(0, len(Mat_a)):
errc=err(p,Mat_a[i],Mat_x[i],Mat_y[i])
err1=np.concatenate((err0,errc))
err0=err1
return err0
Actual fitting and displaying results:
p_global=[1,1,1]
p_best,success=optimize.leastsq(err_global, p_global,args=(Mat_angle,Mat_xdata,Mat_ydata),maxfev=40000)
toplot=[]
for i in range(0,len(Mat_angle)):
toplot.append(lor_func(Mat_xdata[i],Mat_angle[i],p_best))
err_toplot=err_global(p_best,Mat_angle,Mat_xdata,Mat_ydata)
print p_best
for i in range(0,len(Mat_angle)):
plt.plot(Mat_xdata[i],Mat_ydata[i],'o',Mat_xdata[i],toplot[i],'-')
plt.show()
And here is what it displays:
Post a Comment for "Fitting Multiple Data Sets Using Scipy.optimize With The Same Parameters"