Skip to main content

numpy.polyfit example

 #%% load package

import numpy as np

import matplotlib.pyplot as plt


#%% example 1: simple second order fitting

# assume y=2x**2

xx = np.arange(-3,3,step=0.2)

yy = 2*xx**2 

yy +=  (np.random.random(len(xx))-0.5)  # add noise

plt.figure(1, dpi=150)

plt.plot(xx, yy, 'ro')


# curve fitting

lin_fit = np.polyfit(xx, yy, 2)

print(lin_fit)


x2 = np.arange(-3,3,step=.01)

y2 = np.polyval(lin_fit, x2)

plt.figure(1)

plt.plot(x2,y2, 'k')

plt.legend(['raw data','fitting curve'])

plt.legend(['raw data','fitting curve'])

plt.plot(x2[np.argmin(y2)], np.min(y2), 'b*', markersize=10)

plt.text(x2[np.argmin(y2)], np.min(y2)-1, 

         'min: (%.2f, %.2f)'%(x2[np.argmin(y2)], np.min(y2)))

plt.axis([-3,3,-2,20])

plt.show()







#=================================================

#%% example 2

# assume y-y0 = a*(x-x0)**2

# --> y = ax**2 - 2a*x0*x + a*x0**2 + y0

# let a=-1, x0=1.2, y0=0.7, i.e. the maximum value is located at (1.2, 0.7)

# --> y = -1x**2 + 2.4x - 0.74


xx = np.arange(-3,3,step=0.2)

yy = -1*xx**2 + 2.4*xx - 0.74 

yy +=  (np.random.random(len(xx))-0.5)  # add noise

plt.figure(2, dpi=150)

plt.plot(xx, yy, 'ro')


# curve fitting

lin_fit = np.polyfit(xx, yy, 2)

print(lin_fit)


x2 = np.arange(-3,3,step=.01)

y2 = np.polyval(lin_fit, x2)

plt.figure(2)

plt.plot(x2,y2, 'k')

plt.legend(['raw data','fitting curve'])

plt.plot(x2[np.argmax(y2)], np.max(y2), 'b*', markersize=10)

plt.text(x2[np.argmax(y2)], np.max(y2)+1, 

         'max: (%.2f, %.2f)'%(x2[np.argmax(y2)], np.max(y2)))

plt.axis([-3,3,-20,3])

plt.show()



==================================

It's noted that the 
x0 = lin_fit[1] / (-2*lin_fit[0])
y0 = y0 = lin_fit[2] - lin_fit[0] * x0**2

https://github.com/Renfong/Python-toolbox/blob/main/np_polyfit_example.py


Comments

Popular posts from this blog

Top hat filter

The top_hat filter can be used to detect the relatively small edges/peaks superimposed on large background signals. The concept came from the EELS workshop during IMC19. Thanks to Prof. Nestor J. Zaluzec. -- // Using Top_hat digital filter to detect the  relatively small edges  //    superimposed on large background signals. // // ref: Ultramicroscopy 18 (1985) 185-190  //      Digital Filters  for Application to Data Analysis in EELS //      by Nestor J. ZALUZEC // Parameters: // win_s: signal window (default:3) // win_b: background window (default:3) //  a_s : amplitude of signal (fixed value) //  a_b : amplitude of background  (fixed value) // Renfong 2018/10/11 // Main function image Top_Hat_Filter(image img, number win_s, number win_b) { // read image string fname=img.GetName() number sx,sy img.getsize(sx,sy) // filter image img2 := imageclone(img)*0 //the area between...

HyperSpy - read the calibration information in a dm3/dm4 file

Some example of dm3 file reading by using Python HyperSpy package, which can read the detail information of the dm file. -- # import packages import numpy as np import hyperspy.api as hs # load file sp=hs.load('sp.dm3') # Read the axis information      # Print all the calibration detail print(sp.axes_manager) ''' <Axes manager, axes: (272|2042)>             Name |   size |  index |  offset |   scale |  units  ================ | ======= | ====== | ======= | ======= | ======                     x |    272 |      0 |       -0 |  0.0025 |     µm   --------------- |  ------ | ----- |  ------ | ------- | ------    Energy loss |  2042 |         | 3.2e+02 |       1 |     eV...

MLLS in matlab

MLLS stands for  multiple linear least squares fitting, which is the common strategy for the solving EELS edge overlapping and which is also built-in the GMS software. The target spectrum Y and the reference spectrum X Y = A * X Assuming Y is 1*256 matrix and we have three reference spectrums, ie, X is 3*256 matrix. So A is 1*3 matrix. The target is to solve A. If Y and X are n*n matrices, we can use the simple formula Y * inv(X) = A * X * inv(X), ie., A = Y * inv(X). However, Y and X are not n*n  matrices, it is necessary to have some trick to solve it. We can multiply the transpose matrix to produce n*n matrix. Y * X' = A * X * X'  (ps X' means the transpose matrix of X) so A = Y * X' * inv(X * X') Here is the Matlab code: =========  % create target spectrum x=0:256; c=[90,120,155]; sig=[5,10,8]; int=[5,10,8]; xn=zeros(size(x)); ref=zeros(length(c),length(x)); factor=rand(size(c))'; for i=1:length(c)     xn=xn+int(i)*ex...