CURVE FITTING USING PYTHON
Aim
Determine the best Curve (linear, quadratic & cubic) that fits to given data Using Python Script
Objective
- Write a code to fit linear and cubic fit polynomial for the cp data
- Plot the linear and cubic fit curves along with the raw data points
- Understand how the value of Cp (specific heat) changes w.r.to temperature
Theory
Curve fitting is the process of constructing a curve or mathematical functions which posses 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 process. Upon solving multiple system of equation, we can find the coefficients using the either by code or by mathematics. Here choosing a best fit is done by following criteria.
- The sum of square due to error (SSE)
- R-square
- Adjusted R-square
- Root mean square error (RMSE)
Python Script
"""
Created on Sun Jul 12 19:29:24 2020
@author: slomo thomas
"""
#curve fit for linear equation
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curve fit function
def func_linear(t,a,b):
return a*t+b
#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()
popt,pcov=curve_fit(func_linear,temperature,cp)
fit_cp=func_linear(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp,color="red",linewidth=3)
plt.title('Specific Heat Vs Temperature')
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
#curve fit for cubic equation
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curve fit function
def func_cubic(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
#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()
popt,pcov=curve_fit(func_cubic,temperature,cp)
fit_cp=func_cubic(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp,color="red",linewidth=3)
plt.title('Specific Heat Vs Temperature')
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
Explanation of the script
- After importing all the necessary modules, cubic functions with the curve equations are defined.
- The read_file function is defined to read and store the column-wise data in temperature and Cp variables. The split function is used to split the line wherever the ',' is found and are stored as two different elements in the values variable.
- The curve_fit function is used to find the best-estimated values for the coefficients in the equation along with their covariance. The values of the coefficients are then passed to the equation along with the temperature values to find the suitable value of Cp. By this, the new value of Cp is found.
Result obtained
Conclusion
It is clear from the above figures that the curve fits better when the degree of the polynomial increases. It can be observed that the deviation of the curve fit with the actual data is more for linear equation and gradually the deviation decreases with the increase in the order of the polynomial. If we consider fourth, fifth-order polynomials, etc then the curve fit will overlap with the actual data.
Another method to get a better fit could be using split wise polynomial.