Week 5 - Curve fitting
Aim: Curve Fitting using Python.
Theory: Curve fitting is the process of constructing a curve, or mathematical function, that has the best t to a series of data points, possibly subject to constraints.
In our program, we will observe that specific heat is a function of temperature. Since we assume that specific heat is constant but in this, we will get to know that specific heat is a function of temperature. Hence, specific heat varies with an increase in temperature. Specific Heat is in KJ/KgK and temperature is in Kelvin(K).
i.e: cp = f(t).
Equations: Basic equation of polynomial are used are as followed;
y = a ⋅ x + b
y = a ⋅ x2 + b ⋅ x + c
y = a ⋅ x3 + b ⋅ x2 + c ⋅ x + d
y = a ⋅ x4 + b ⋅ x3 + c ⋅ x2 + d ⋅ x + e
a, b, c, d & e are arbitrary constants.
Procedure:
- In this program, the first line we will use is a comment statement and then we will start importing the libraries like math, scipy, matplotlib and numpy.
- Then we will dene the function for the polynomial in which at first we will take all the variable and constant.
- Now we will read the data le and import the temperature and cp value.
- Now we will start the curve fitting in which we will first read the thermodynamic data le and then we will nd out the arbitrary constant value of the polynomial equation.
- Then we will nd the error percentage.
- At last, we will plot the actual data and the curve fit data line.
- We will do this process for the second order, third order, and fourth-order polynomial t.
Program Code:
1st Order Curve Fit
#Linear Curve Fitting
import math
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
#Fitting Function
def func(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,temperature,cp) fit_cp = func(np.array(temperature),*popt)
#Error1
Error1 = abs((cp-fit_cp)/cp)*100
err1 = max(Error1)
print(err1)
plt.plot(temperature, cp, color= 'blue',linewidth =3)
plt.plot(temperature, fit_cp, color = 'red',linewidth = 3)
plt.legend(['actual data','curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
2nd Order Curve Fit:
#Squared Curve Fitting
import math
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
#Fitting Function
def func(t,a,b,c):
return a*pow(t,2)+b*t+c
#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,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
#Error1
Error1 = abs((cp-fit_cp)/cp)*100
err1 = max(Error1)
print(err1)
plt.plot(temperature, cp, color= 'blue',linewidth =3)
plt.plot(temperature, fit_cp, color = 'red',linewidth = 3)
plt.legend(['actual data','curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
3rd Order Curve fit:
#Cubic Curve Fitting
import math
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
#Fitting Function
def func(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,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
#Error2
Error2 = abs((cp-fit_cp)/cp)*100
err2 = max(Error2)
print(err2)
plt.plot(temperature, cp, color= 'blue',linewidth =3)
plt.plot(temperature, fit_cp, color = 'red',linewidth = 3)
plt.legend(['actual data','curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
4th Order Curve fit:
#fourth Order Curve Fitting
import math
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
#Polynomial Fitting Function
def func(t,a,b,c,d,e):
return a*pow(t,4)+b*pow(t,3)+c*pow(t,2)+d*t+e
#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,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
#Error3
Error3 = abs((cp-fit_cp)/cp)*100
err3 = max(Error3)
print(err3)
plt.plot(temperature, cp, color= 'blue',linewidth =3)
plt.plot(temperature, fit_cp, color = 'red',linewidth = 3)
plt.legend(['actual data','curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
Results and Plots:
1st Order Curve fit:
2nd Order Curve fit:
3rd Order Curve fit:
4th Order Curve fit:
Conclusion:
When we go to 3rd degree polynomial from 2nd degree polynomial and 1st degree polynomial the error decreases but when we go to 4th order polynomial error increases as compared to 3rd degree polynomial. Hence we can conclude that it does not essentially necessary that if we go for higher polynomial error will reduce. Hence, 3rd order polynomial is best t for this curve.
Questions:
1.What doe popt and pcov mean?
Ans: popt- An array of optimal values for the parameters which minimize the sum of squares of residuals. pcov-2d array which contains the estimated covariance of popt.
2.What does np.array(temperature) do?
Ans: NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array has.
3.What does the *in *popt mean?
Ans: popt stores all the value for constraints in the function and the *(star) refers to the address of all the constraints.
4. What needs to be done in order to make the curve fit perfectly?
Ans: In order to make perfect t, we must consider error estimates as well. Perfect t means, the curve should t the original curve without showing any errors (such as centering and scaling errors) in that particular degree of a polynomial. Perfect t can always be the best t but best t cannot be a perfect fit.