Created
November 11, 2016 15:00
-
-
Save mstankie/1b2cabe10329b387391fee2a192592cc to your computer and use it in GitHub Desktop.
Fitting two curves with some common parameters.
From http://scipy-cookbook.readthedocs.io/items/FittingData.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Target function | |
fitfunc = lambda T, p, x: p[0]*np.cos(2*np.pi/T*x+p[1]) + p[2]*x | |
# Initial guess for the first set's parameters | |
p1 = r_[-15., 0., -1.] | |
# Initial guess for the second set's parameters | |
p2 = r_[-15., 0., -1.] | |
# Initial guess for the common period | |
T = 0.8 | |
# Vector of the parameters to fit, it contains all the parameters of the problem, and the period of the oscillation is not there twice ! | |
p = r_[T, p1, p2] | |
# Cost function of the fit, compare it to the previous example. | |
errfunc = lambda p, x1, y1, x2, y2: r_[ | |
fitfunc(p[0], p[1:4], x1) - y1, | |
fitfunc(p[0], p[4:7], x2) - y2 | |
] | |
# This time we need to pass the two sets of data, there are thus four "args". | |
p,success = optimize.leastsq(errfunc, p, args=(Tx, tX, Ty, tY)) | |
time = np.linspace(Tx.min(), Tx.max(), 100) # Plot of the first data and the fit | |
plt.plot(Tx, tX, "ro", time, fitfunc(p[0], p[1:4], time),"r-") | |
# Plot of the second data and the fit | |
time = np.linspace(Ty.min(), Ty.max(),100) | |
plt.plot(Ty, tY, "b^", time, fitfunc(p[0], p[4:7], time),"b-") | |
# Legend the plot | |
plt.title("Oscillations in the compressed trap") | |
plt.xlabel("time [ms]") | |
plt.ylabel("displacement [um]") | |
plt.legend(('x position', 'x fit', 'y position', 'y fit')) | |
ax = plt.axes() | |
plt.text(0.8, 0.07, | |
'x freq : %.3f kHz' % (1/p[0]), | |
fontsize=16, | |
horizontalalignment='center', | |
verticalalignment='center', | |
transform=ax.transAxes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment