Week 5 - Curve fitting
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#linear curve fit function
def func(t,a,b):
return a*t + b
#reading the data file
def read_file():
temperature = []
cp = []
for line in open('data','r'):
values = line.split(',')
temperature.append(float(values[0]))
cp.append(float(values[1]))
return [temperature,cp]
temperature,cp=read_file()
popt,pcop = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt) #calculations of predicted cp or predict the cp through linear equation
#print(popt)
#print(pcop)
#plot the data from file vs predicted cp
plt.plot(temperature, cp,color='blue', linewidth=3)
plt.plot(temperature,fit_cp,color='red',linewidth=3)
plt.legend(['actual data','linear curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('specific heat at constant pressure Cp')
plt.savefig('plot 1')
plt.grid()
plt.show()
#calculate the R_square for goodness of curve
#SSE is sums of square due to errors
SSE=np.sum(pow(np.array(np.array(cp)-np.array(fit_cp)),2))
#SSR is sum of square of reegression
SSR = np.sum(pow(np.array(fit_cp)-(np.mean(np.array(cp))),2))
#SST total sums of square
SST = SSE + SSR
R_square = SSR/SST
print('(R_square)goodness of curve fit in linear curve =',R_square )
#cubic curve fit function
def func(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
temperature,cp=read_file()
popt,pcop = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt) #calculations of predicted cp or predict the cp through linear equation
#print(popt)
#print(pcop)
plt.figure(2)
plt.plot(temperature, cp,color='blue', linewidth=3)
plt.plot(temperature,fit_cp,color='red',linewidth=3)
plt.legend(['actual data','Cubic curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('specific heat at constant pressure Cp')
plt.savefig('plot 2')
plt.grid()
plt.show()
#calculate the R_square for goodness of curve
#SSE is sums of square due to errors
SSE=np.sum(pow(np.array(np.array(cp)-np.array(fit_cp)),2))
#SSR is sum of square of reegression
SSR = np.sum(pow(np.array(fit_cp)-(np.mean(np.array(cp))),2))
#SST total sums of square
SST = SSE + SSR
R_square = SSR/SST
print('(R_square)goodness of curve fit in cubic curve =',R_square )
Objectives:
- What does popt and pcov mean? (Watch the video to get some context)
- What does np.array(temperature) do?
- What does the * in *popt mean?
- Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
- What needs to be done in order to make the curve fit perfect?
- Show empirically as to how well your curve has been fit.
Solution :
Step wise explaination of curve fitting program
- First of all as we do in our every step we must import libraries like import math , import matplotlib.pyplot as plt, import numpy as np, from scipy.optimize import curve_fit as we requires curve fit in this problem.
- Next we create a linear equation function to make basic curve from given data by using syntax : def func(t,a,b): and then return it to linear equation by using syntax: return a*t+b
- Now we have the file given in challenge which we have to use in our code so its time to use the file means read it or open it so we use the user define function to read it. To open the file we use the syntax “ for line in open(‘file name’,’r’) “ r stand for read. Next we need different columns for different parameters like on x we need temperature and for temp data we need first column , and for y we need specific heat which is our second column so we use float(line.split(0)) command for temperature and float(line.split(1)) command for specific heat(cp)
- Now our file is open and parameters are defined to it so we get those (temperature, cp ). Now we gonna calculate coefficients using the syntax : popt,pcov(func,temperature,cp) in which we use the function “func” which we created above of linear equation hence we get our predicted cp from above equation and syntax (Pcov is a command which tells the degree of polynomial , popt is the variable which stores the coefficient)
- Next we are going to plot those things so first we plot the curve using the data we have in file which was our actual data plot and then we gonna plot another curve of our linear predicted Cp curve
- Now we need cubic curve so we just gonna copy above func basically and then make some slight changes in those equation converting linear to cubic form , hence we chande a*t+b to a*pow(t,3) + b*pow(t,2) + c*t + d and then plot those with same set of ploting syntax which we used above
- Now we need goodness of curve for which we use the “ R_square “ method in this method if R_square is near about 0 then that is seaid to be bad quality of curve fit and if it is goanna near 1 then it is said to be perfectly fit so these R-square lies between 0 – 1
- R-square is the ratio of SSR to SST and SST is SSR + SSE so we make some calculations to calculate R-square and we need to calculate this for both linear and cubic curve
Results :
(R_square)goodness of curve fit in linear curve = 0.9248776260524184
(R_square)goodness of curve fit in cubic curve = 0.9967259467146888
Questions answers
- Pcov is a command which tells the degree of polynomial , popt is the variable which stores the coefficient
- array(temperature) does the array stored in the name of temperature (like we get the temperature data from data file so after taking those data if we say np.array(temperature) then it shows the full column in array form.
- popt is the variable syntax which stores the coefficient in it
- as our R_square of both the linear and cubic are near about 0.9 we can say that bot are fitted good but cubic curve is more perfect than linear as its values lies near about 0.99
- to make curve fit perfectly we need to increase the degree of polynomial and we need our R_square should be more near to 1 or greater than 0.95
- as we seen in plots and r_square we get the curve more perfect and good in cubic curve so seeing those curve and R-square our R-square of cubic curve is 0.9967 so it is said to be perfectly fit.