Week 5 - Curve fitting
OBJECTIVE:
To perform curve fitting based on the given set of datasets.
PROBLEM STATEMENT
- Write code to fit a linear and cubic polynomial for the Cp data.
- Write code to fit a linear and cubic polynomial for the Cp data.
- Explain the parameters given above.
THEORY:
Curve fitting is the process of plotting a curve such that it passes through most of the dataset point for a data having numerous values or points (Big data). Thereby, bringing a proper shaped graph of the data which can be interpreted for further references.
PYTHON PROGRAM:
#Curve Fitting Using Python
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#Curve fit Function
def func_linear(t,a,b):
return a*t + b
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()
#Linear Curve Fit
popt, pcov =curve_fit(func_linear, temperature, cp)
fit_cp1 = func_linear(np.array(temperature), *popt)
#Cubic Curve Fit
popt, pcov =curve_fit(func_cubic, temperature, cp)
fit_cp2 = func_cubic(np.array(temperature), *popt)
#Determining Goodness of Fit
#Linear Curve Fit
mean_cp = np.mean(cp)
error = np.array(cp) - np.array(fit_cp1)
#Curve Fitness Parameters
SSE_Linear = np.sum(pow(error, 2))
regression = np.array(cp) - mean_cp
SSR_Linear = np.sum(pow(regression,2))
SST_Linear = SSE_Linear + SSR_Linear
Rsquare_Linear = SSR_Linear/SST_Linear
print("Fitness of Linear Curve Fit")
print('SSE_Linear =',SSE_Linear)
print('SSR_Linear =',SSR_Linear)
print('SST_Linear =',SST_Linear)
print('Rsquare_Linear =', Rsquare_Linear)
if 1>Rsquare_Linear>0.9:
print('Good Fit')
else:
print('Bad Fit')
print(' ')
plt.figure(1)
plt.plot(temperature, cp, 'b--', linewidth = 3)
plt.plot(temperature, fit_cp1, 'r-', linewidth = 3)
plt.title('Linear Curve Fit')
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Specifit Heat[kJ/kgK]')
plt.savefig('Linear Curve Fit')
plt.show()
# Cubic Fit
mean_cp = np.mean(cp)
error = np.array(cp) - np.array(fit_cp2)
#Fitness Parameters
SSE_cubic = np.sum(pow(error, 2))
regression = np.array(cp) - mean_cp
SSR_cubic = np.sum(pow(regression,2))
SST_cubic = SSE_cubic + SSR_cubic
Rsquare_cubic = SSR_cubic/SST_cubic
print("Fitness of Cubic Curve Fit")
print('SSE_cubic =',SSE_cubic)
print('SSR_cubic =',SSR_cubic)
print('SST_cubic =',SST_cubic)
print('Rsquare_cubic =', Rsquare_cubic)
if 1>Rsquare_cubic>0.9:
print('Good Fit')
else:
print('Bad Fit')
print(' ')
plt.figure(2)
plt.plot(temperature, cp, 'b--', linewidth = 3)
plt.plot(temperature, fit_cp2, 'r-', linewidth = 3)
plt.title('Cubic Curve Fit')
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Specifit Heat[kJ/kgK]')
plt.savefig('Cubic Curve Fit')
plt.show()
#print(max(Rsquare_Linear,Rsquare_cubic))
#print('Best Fit')
if Rsquare_cubic>Rsquare_Linear:
print(Rsquare_cubic)
print('CUBIC CURVE FIT IS THE BEST FIT')
else:
print(Rsquare_Linear)
print('LINEAR CURVE FIT IS THE BEST FIT')
SOLUTION PROCEDURE:
- Import the required libraries into the program file.
- Define the Linear and Cubic function and return the function.
- In order to read the data from the file define data file.
- Create empty arrays of temperatures and Cp.
- Using for loop the data is read line by line.
- Then the values in the data are splitter based on the location of 'comma'.
- The first column values i.e left of the comma are appended in float form into the temperature array.
- The second column values i.e to the right of the comma are appended in float form into the cp array.
- Now, temperature and cp values are obtained from the data file.
- Calculate the Curve for the defined Linear and Cubic polynomial by using curve_fit function imported from scipy module.
- The function of popt and pcov is explained below.
- Then the Fitness parameters like Sum of Square of errors, R square and Sum of square about the mean values are calculated and printed.
- The Linear and Cubic curve fit is plotted.
- The best fit is the one which has a higher R square value.
THEORY QUESTION EXPLANATION:
1. What does popt and pcov mean?
popt - It is the output of the function defined which gives the values of the coefficients (or) unknowns in that function.
pcov - matrix which consists of estimated covariance of popt.
2. What does np.array(temperature) do?
np.array(temperature) is used to create an array of temperature in which the different temperature values extracted from the data file are stored in a proper syntaxial way.
3. What does the * in *popt mean?
As popt contains the values of unknown coefficient in the defined function '*' helps us to refer these stored values of the unknowns.
4. What needs to be done in order to make the curve fit perfect?
A curve can be made to fit perfectly by comparing the criterias 'sum of squares due to error (SSE) and 'R square' values obtained for various fits. A fit is perfect if the SSE value is lesser(nearer to 0) and if the R square value is greater (nearer to 1).
RESULTS AND DISCUSSIONS:
OUTPUT SCREEN
As Rsquare value of cubic fit is greater than that of Linear Curve Fit and SSE value of Cubic Curve fit is less than that of Linear Curve Fit. Cubic Fit is the best among the two fits.
CURVE FIT PLOTS