Week 5 - Curve fitting
AIM: To write a python code to fit the best curve for the given data (i.e., a linear and cubic polynomial for the Cp (specific heat) data).
THEORY: Curve fitting is a process of constructing a curve, or a mathematical function, that has the best fit to a series of data points, possibly subject to constraints.
SOLUTION PROCEDURE:
This project consists of specific heat (Cp) values, and temperature is given as input. The curve is plotted for Cp as the function of temperature using different degrees of polynomial functions such as linear, quadratic, cubic… etc.
Plots are created using python code and compared with the actual plot.
After comparison, we are going to figure out the best possible ways to have a perfect fit.
---------------------------------------------------------------------------------------------------
popt: It is the output of the curve-fit function. It gives the values of the coefficients involved in the mathematical model that provides a relationship between specific heat (Cp) and temperature.
It gives an array with the optimal values for the parameters so that the sum of the squared residuals of data is minimized.
pcov: It is a 2d array with the estimated covariance of the parameters in popt. Can use it to calculate the standard deviation errors of popt.
While a covariance refers to the measure of direct relationship between two random variables.
np.array(temperature): This function contains (stores) the temperature values in the form of an array and passes it to the function numpy.
*popt: We know that the popt contains the values of coefficients involved in the polynomial functions. Using this star (*), is used to refer to these values, and it stores these values in the array popt.
CODE WITH EXPLAINATION: codes for linear, quadratic, and cubic curve fits are separated with ---- line. While grading, please execute the codes separately.
# CURVE FIT FOR LINEAR FUNCTION BY SAMBA MAHESH
# IMPORTING MODULES REQUIRED FOR CURVE FITTING
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# CURVE FIT FUNCTION
def func(t,a,b):
return a*t+b # using LINEAR POLYNOMIAL FUNCTION.
# READING THERMODYNAMIC DATA FILE
def read_file():
temperature=[] # Creating an empty array of temperature.
cp=[] # Creating an empty array of specific heat (cp)
for line in open('data','r'): # using for loop to open the data file and 'r' means reading mode.
values=line.split(',') # using line.split to split the values of temperatures and cp with comma in every line.
temperature.append(float(values[0])) # Appending the values to the created array of temperature.
cp.append((float(values[1]))) # Appending the values to the created array of specific heat(cp).
return(temperature,cp) # returning the function
# MAIN PROGRAM
temperature,cp=read_file() # Calling the function
popt, pcov= curve_fit(func, temperature, cp) # performing the curve fit and also calculating the values of coefficients involved in mathematical model representing the curve fit.
fit_cp= func(np.array(temperature), *popt) # Passing the calculated values to the defined function.
# Plotting the obtained results.
plt.plot(temperature,cp,color="blue",linewidth=3) # ACTUAL PLOT
plt.plot(temperature,fit_cp,color="red",linewidth=3) # CURVE_FIT
# labeling the plot
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Cp [KJ/Kg-K]')
plt.show()
-----------------------------------------------------------
# CURVE FIT FOR QUADRATIC FUNCTION BY SAMBA MAHESH
# IMPORTING MODULES REQUIRED FOR CURVE FITTING
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# CURVE FIT FUNCTION
def func(t,a,b,c):
return a*t**2+b*t+c # using QUADRATIC POLYNOMIAL FUNCTION.
# READING THERMODYNAMIC DATA FILE
def read_file():
temperature=[] # Creating an empty array of temperature.
cp=[] # Creating an empty array of specific heat (cp)
for line in open('data','r'): # using for loop to open the data file and 'r' means reading mode.
values=line.split(',') # using line.split to split the values of temperatures and cp with comma in every line.
temperature.append(float(values[0])) # Appending the values to the created array of temperature.
cp.append((float(values[1]))) # Appending the values to the created array of specific heat(cp).
return(temperature,cp) # returning the function
# MAIN PROGRAM
temperature,cp=read_file() # Calling the function
popt, pcov= curve_fit(func, temperature, cp) # performing the curve fit and also calculating the values of coefficients involved in mathematical model representing the curve fit.
fit_cp= func(np.array(temperature), *popt) # Passing the calculated values to the defined function.
# Plotting the obtained results.
plt.plot(temperature,cp,color="blue",linewidth=3) # ACTUAL PLOT
plt.plot(temperature,fit_cp,color="red",linewidth=3) # CURVE_FIT
# labeling the plot
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Cp [KJ/Kg-K]')
plt.show()
-----------------------------------------------
# CURVE FIT FOR CUBIC FUNCTION BY SAMBA MAHESH
# IMPORTING MODULES REQUIRED FOR CURVE FITTING
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# CURVE FIT FUNCTION
def func(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d # using CUBIC POLYNOMIAL FUNCTION.
# READING THERMODYNAMIC DATA FILE
def read_file():
temperature=[] # Creating an empty array of temperature.
cp=[] # Creating an empty array of specific heat (cp)
for line in open('data','r'): # using for loop to open the data file and 'r' means reading mode.
values=line.split(',') # using line.split to split the values of temperatures and cp with comma in every line.
temperature.append(float(values[0])) # Appending the values to the created array of temperature.
cp.append((float(values[1]))) # Appending the values to the created array of specific heat(cp).
return(temperature,cp) # returning the function
# MAIN PROGRAM
temperature,cp=read_file() # Calling the function
popt, pcov= curve_fit(func, temperature, cp) # performing the curve fit and also calculating the values of coefficients involved in mathematical model representing the curve fit.
fit_cp= func(np.array(temperature), *popt) # Passing the calculated values to the defined function.
# Plotting the obtained results.
plt.plot(temperature,cp,color="blue",linewidth=3) # ACTUAL PLOT
plt.plot(temperature,fit_cp,color="red",linewidth=3) # CURVE_FIT
# labeling the plot
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Cp [KJ/kg-K]')
plt.show()
RESULTS AND DISCUSSIONS:
linear fit :

Quadratic fit:

Cubic fit:

It is clear from the above figures that the curve fits better when the degree of the polynomial increases. can 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 and more higher-order polynomials, the curve fit will overlap with the actual data.
We can also fit the best curve by splitting the polynomial function by using python.