CURVE FITTING using PYTHON
AIM: To perform curve fitting for a given temperature and specific heat data of Oxygen species using PYTHON.
OBJECTIVES: To write code to fit a linear and cubic polynomial for the given Cp data.
Curve Fitting:
Curve fitting is the process of constructing a curve or mathematical functions, which posses the closest proximity to the real series of data.
The Programming Language Used: PYTHON
CODE:
#IMPORT THE MODULES
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#Reading thermodynamic 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]
#main program
temperature, cp = read_file()
#CASE 1 LINEAR FIT
#curve fit function
def fun_deg1(t, a, b):
return a*t+b
#calculating the coeffients
popt, pcov = curve_fit(fun_deg1, temperature, cp)
fit_cp = fun_deg1(np.array(temperature),*popt)
#plotting
plt.figure(1)
plt.plot(temperature,cp,'b-',label='actual data',Linewidth=6)
plt.plot(temperature,fit_cp,'r-',Linewidth=6,
Label='linear curve fit: a=%5.3f,b=%5.3f' %tuple(popt))
plt.legend(loc='best')
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('LINEAR CURVE FIT')
#Computing the R-Square
#R is pearson corelation
corelation_matrix=np.corrcoef(cp,fit_cp)
corelation=corelation_matrix[0,1]
R_squared=pow(corelation,2)
print('Goodness of LINEAR curve fit (R_squared) is:',R_squared)
#CASE 2: CUBIC FIT
#curve fit function
def fun_deg3(t, a, b, c, d):
return a*(t**3)+b*(t**2)+c*t+d
#computing the coefficients
popt, pcov = curve_fit(fun_deg3, temperature, cp)
fit_cp = fun_deg3(np.array(temperature),*popt)
#plotting
plt.figure(2)
plt.plot(temperature,cp,'b-',label='actual data',Linewidth=6)
plt.plot(temperature,fit_cp,'r--',Linewidth=6,
Label='cubic curve fit: a=%5.4f,b=%5.4f,c=%5.4f,d=%5.4f' %tuple(popt))
plt.legend(loc='best')
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('CUBIC CURVE FIT')
#Computing the R-Square
#R is pearson corelation
corelation_matrix=np.corrcoef(cp,fit_cp)
corelation=corelation_matrix[0,1]
R_squared=pow(corelation,2)
print('Goodness of CUBIC curve fit (R_squared) is:',R_squared)
#CASE 3: TESSERACT FIT
#curve fit function
def func_deg4(t, a, b, c, d , e):
return a*(t**4)+b*(t**3)+c*(t**2)+d*t+e
#computing the coefficients
popt, pcov = curve_fit(func_deg4, temperature, cp)
fit_cp = func_deg4(np.array(temperature),*popt)
#plotting
plt.figure(3)
plt.plot(temperature,cp,'b-',label='actual data',Linewidth=6)
plt.plot(temperature,fit_cp,'r--',Linewidth=6,
Label='tessaract curve fit: a=%5.4f,b=%5.4f,c=%5.4f,d=%5.4f,e=%5.4f' %tuple(popt))
plt.legend(loc='best')
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('TESSARACT CURVE FIT')
#Computing the R-Square
#R is pearson corelation
corelation_matrix=np.corrcoef(cp,fit_cp)
corelation=corelation_matrix[0,1]
R_squared=pow(corelation,2)
print('Goodness of TESSERACT curve fit (R_squared) is:',R_squared)
plt.show()
EXPLANATION TO THE CODE:
- Create a new file and import the modules like matplotlib, numpy and curve_fit.
- extract the temperature, cp values from data file using for loop and read_file function.
- define the functions for polynomial and compute the coefficients using curve_fit function.
- plot the original data set with computed data set every time.
- compute the person correlation and thereby coefficient of determination (R-square) to find the goodness of the fit.
- R-square value always lies between 0 and 1
- If R-square value is greater than 0.95 curve fit is assumed to be a good fit else bad fit.
- tesseract curve fit has R-square value 0.9996>0.95, so it is is a good fit
- where linear fit value is 0.9248<0.95, so it is a bad fit.
RESULTS:
Linear fit
Cubic fit
Tesseract fit
R-squared values
Conclusions:
The polynomial of degree 4 is the best for the given data as R-square is (0.99961>0.95) very close to 1.
1. What do popt and pcov mean? (Watch the video to get some context)
- The
curve_fitfunction returns two items,poptandpcov. - popt computes the coefficients for the polynomial cp which is a function of temperature, for different orders. Its computation is based on the least-squares method.
- popt: array
It returns optimal values for the parameters so that the sum of the squared residuals of is minimized.
pcov2-D arrayIt contains the estimated covariance of popt. It can be used to find the standard deviation of fitting parameters. The diagonals provide the variance of the parameter estimate.
-
The
pcovvariable contains the covariance matrix, which indicates the uncertainties and correlations between parameters.
2. What does np.array(temperature) do?
- To pass the temperature as an array to the defined function, we have to use the numpy module np.array(temperature). Here numpy is imported as np.
3. What does the * in *popt mean?
- The * notation will expand a list of values into the arguments of the function.
- This is useful to pass a function which has more than one or two parameters.
4. What needs to be done in order to make the curve fit perfect?
- To make the curve fit better we can use splitwise method, or we can normalize the distributed data (temperature) and go for higher-order polynomials.
- We have to eliminate the errors associated with the curve fit by taking them it account and choosing the best coefficient of determination (R-squared) close to 1.