Curve fitting Using Python
Aim:To write a code in python to fit a linear and cubic polynomial for the Cp data
Theory:
Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values etc. It is highly effective in the mathematical modelling of some natural processes.
Fitting functions to data points
Most commonly, one fits a function of the form y=f(x).
1.The first degree polynomial equation is y=ax+b
2.The second degree polynomial equation is y=ax2+bx+c
3.The third degree polynomial equation is y=ax3+bx2+cx+d
Link for the file:
https://drive.google.com/file/d/1vWi9Vj3AdQf0gqUK1u9jwS8zg92BHGR0/view
Code:
#curve fitting
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#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]
#linear fit
def func(t,a,b):
return a*t+b
temperature,cp=read_file()
popt,pocv=curve_fit(func,temperature,cp)
fit_cp_linear=func(np.array(temperature),*popt)
#plotting
plt.figure(1)
plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp_linear,color='red',linewidth=3)
plt.legend(['Actual data','Linear Fit'])
plt.title('Temperature vs Specific Heat')
plt.xlabel('Temperature[K]')
plt.ylabel('Specific Heat')
plt.show()
#cubic fit
def func(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
temperature,cp=read_file()
popt,pocv=curve_fit(func,temperature,cp)
fit_cp_cubic=func(np.array(temperature),*popt)
#plotting
plt.figure(2)
plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp_cubic,color='red',linewidth=3)
plt.legend(['Actual data','Cubic Fit'])
plt.title('Temperature vs Specific Heat')
plt.xlabel('Temperature[K]')
plt.ylabel('Specific Heat')
plt.show()
#comparision of linear and cubic curve fit
plt.figure(3)
plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp_linear,color='red',linewidth=3)
plt.plot(temperature,fit_cp_cubic,color='green',linewidth=3)
plt.legend(['Actual data','Linear Fit','Cubic Fit'])
plt.title('Temperature vs Specific Heat')
plt.xlabel('Temperature[K]')
plt.ylabel('Specific Heat')
plt.show()
Explanation of code:
1.Required libraries namely numpy , scipy.optimize and matplotlib.pyplot are imported.
2.The file is read using the read function,its values is seperated using split function and stored in two different arrays called temperature and Cp.
3.Defining function to accept the values of t,a,b,c and d and return the value after calculating by using them in the cubic and linear equations.
4.popt and pcov values are found out using curve_fit function.Further the calculated values are stored by calling func function for linear equations and cubic equations and stored in fit_cp_linear and fit_cp_cubic respectively.
5. A graph 'Temperature vs Specific Heat' is plotted to compare the original dataset and linear fit curve.
6.A graph 'Temperature vs Specific Heat’ is plotted to compare the original dataset and cubic fit curve.
7.A graph is plotted to compare the original dataset, linear fit curve and cubic fit curve.
Plots:
Plot for the linear fit curve along with the raw data points
Plot for the cubic fit curve along with the raw data points
Plot to compare the original dataset, linear fit curve and cubic fit curve
Errors Obtained: Simple errors were obtained and were rectified easily
Conclusion:
From the plots for linear and cubic curve fits , it can be observed that by increasing the order of the polynomial the error between the curve fit and the original dataset is reduced.
Extra Questions:
1.What does popt and pcov mean?
popt is an array of optimal values for the parameters which minimizes the sum of squares of residuals.
pcov is a 2d array with the estimated covariance of the parameters in popt.
2.What does np.array(temperature) do?
It is used for passing the values of temperature as a numpy array.
3.What does the * in *popt mean?
In *popt the * symbol is used to unpack the array and supply arguments for remaining parameters.
4.What needs to be done in order to make the curve fit perfect?
The fit is perfect when R2 value is exactly equal to 1.This is obtained when the predicted curve and the original dataset curve meet at all the points. So, we need to increase the order of the polynomial for the curve to fit perfectly .