I have six datasets, I wish to fit all six datasets simultaneously, with two parameters common between the six datasets and one to be fit seperately.
I'm planning to fit a simple ax**2+bx+c polynomial to the datasets, where a and b is shared between the six datasets and the offset, c, is not shared between the six.
Therefore I'm fitting a common slope between the datasets but with a variable offset.
I'm fully competent in fitting them individually, however as the slopes are similar between each dataset, the error on the offset, c, would be greatly improved using simultaneous fitting.
I typically fit using the scipy.optmize.curve_fit.
import numpy as np
from scipy.optimize import curve_fit
def func(x,a,b,c):
return (a*(x**2)+b*x+c)
def fit(x,y,yerr):
popt, pcov = curve_fit(func,x,y,p0=[-0.6,5,-12],sigma=yerr)
chi=np.sum( ((func(x, *popt) - y) / yerr)**2)
redchi=(chi-1)/len(y)
return popt,pcov,redchi,len(y)
I'm handling 6 sets of: x,xerr,y,yerr len(x) and len(y) is different for each set.
I understand I have to concatenate the datasets and fit them this way.
If anyone can offer any advice or help, I'm sure it would be beneficial for both me and the community.
Thanks for all the suggestions, I seem to have found a way to fit them simultaneously with a,b and c1,c2,c3,c4,c5,c6 as the parameters, where a and b are shared.
Below is the code I used in the end:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
x=[vt,bt,ut,w1t,m2t,w2t]
y=[vmag,bmag,umag,w1mag,m2mag,w2mag]
xerr=[vterr,uterr,bterr,w1terr,m2terr,w2terr]
yerr=[vmagerr,umagerr,bmagerr,w1magerr,m2magerr,w2magerr]
def poly(x_, a, b, c1, c2, c3, c4, c5, c6):
#all this is just to split x_data into the original parts of x
l= len(x[0])
l1= len(x[1])
l2= len(x[2])
l3= len(x[3])
l4= len(x[4])
l5= len(x[5])
s=l+l1
s1=l2+s
s2=l3+s1
s3=l4+s2
s4=l5+s3
a= np.hstack([
a*x_[:l]**2 + b*x_[:l] +c1,
a*x_[l:(s)]**2 + b*x_[l:(s)] +c2,
a*x_[(s):(s1)]**2 + b*x_[(s):(s1)] +c3,
a*x_[(s1):(s2)]**2 + b*x_[(s1):(s2)] +c4,
a*x_[(s2):(s3)]**2 + b*x_[(s2):(s3)] +c5,
a*x_[(s3):(s4)]**2 + b*x_[(s3):(s4)] +c6
])
print a
return a
x_data = np.hstack([x[0],x[1],x[2],x[3],x[4],x[5]])
y_data = np.hstack([y[0],y[1],y[2],y[3],y[4],y[5]])
(a, b, c1, c2, c3, c4, c5, c6), _ = curve_fit(poly, x_data, y_data)
Apologies if this is awful coding! I'm very rough with my approach! However, it certainly does the job well!
Below is my resulting fit.
Fitted results from simultaneous fitting with shared parameters