Week 5 - Curve fitting
INTRODUCTION
Curve fitting is the process of constructing a mathematical function which best fits a set of data points subjecting to some constraints. A set of data points which consist of the Temperature and the specific heat at constant pressure is obtained and a function is generated which best suits the curve.
AIM
In this challenge, a curve fit is done using the scipy library in python.
RESULTS AND CODE
The stepwise explanation of the code is given below:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
The above snippet of code imports the required libraries. From the optimize module of the scipy library curve_fit function is imported for curve fitting.
# Defining function
def func(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
The above snippet of code generates a cubic function with parameters a, b, c and d which is one of the parameters that is needed for the curve_fit() function.
# Defining 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 ]
The above snippet of code reads a data file and extracts data and stores in arrays temp and cp. The string files from the data file are converted into float. The function returns a 2D array.
temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
print(popt)
print(pcov)
popt and pconv are the values returned by scipy.optimize.curve_fit. The value returned in popt is a 1d array which consists of the optimal values for the parameters so that the sum of the squared residuals is minimized. The values returned by pconv is a 2D array which returns the optimized covariance of opt. The statement np.array(temperature) passes an array consisting of the values of temperature. The * in *popt is used to refer the parameters in popt and is passed to the function func().
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(r'$C_p [kJ/kgK]$')
plt.show()
The above snippet of code is used to plot the curve fit data and the original data.
The curve fit data and the actual data gives a perfect match when a cubic polynomial was used. The complete code is given below.
"""
Curve fit using scipy
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# Defining function
def func(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
# Defining 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 ]
temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
print(popt)
print(pcov)
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(r'$C_p [kJ/kgK]$')
plt.show()
CONCLUSION
The code for curve fitting was written in python and the plot is generated.