Program to perform curve fitting in Python
AIM-
Program to perform curve fitting in Python.
Introduction-
1. Defining functions-
- math and matplotlib.pyplot were imported for using mathematical functions and plotting. numpy was imported to do mathematical operations on arrays and curve_fit was imported to fit the given points according to the specified equation.
- A linear function (a⋅t+b">a⋅t+ba⋅t+b) and a cubic function (a⋅t3+b⋅t2+c⋅t+d">a⋅t3+b⋅t2+c⋅t+da⋅t3+b⋅t2+c⋅t+d) was defined. The given data set will be plotted according to these equations.
- Another function (read_file) was defined to read values from the data file. Two separate arrays for the two parameters (temperature and Cp) were formed. 'open' function was used to read the values from the file and values of temperature and Cp were appended to the arrays previously formed using a loop.
2. Plotting curves-
- The 'read_file' function was called to input all temperature and Cp values in their respective arrays.
- 'curve_fit' command is used to plot the curve using the defined functions and the temperature and Cp arrays as the input. The optimal values of the coefficients of the defined curve equations are stored in 'popt' as an array.'pcov' stores the values of covariance of the coefficients in 'popt' in the form of a 2D array.
- The new Cp array for the curve is obtained by using the temperature and calculated coefficients as input in the defined function.'np.array(temperature)' gives the data points of temperature as an array and '*popt' gives the values of coefficients of the defined function.
- The above-mentioned process for curve plotting was repeated for both linear and cubic functions. The fitted curve for both the cases is plotted along with the curve formed by original Cp and temperature values for comparison.
- In order to form a better fit, a third curve was plotted by using a linear function and splitting the data set into multiple parts. This was done by forming a loop and then repeating the curve fitting process for only 400 data points at a time. Thus, a curve represented by eight linear lines was formed.
3. Calculating errors-
- To check how good the curve fit given by the program is, values root mean square error(RMSE) and R2">R2R2 were calculated.
- RMSE is a measure of the average deviation of the Cp from the data file values.
- The R2">R2R2 value indicates the percentage of variability in Cp that is explained by the model.
- The formulas to calculate these values are as follows:
- RMSE=SSEn">RMSE=√SSE/nwhere 'SSE' is the sum of squared errors and 'n' is the number of data points
- R2=SSRSST">R2=SSR/SSTwhere 'SSR' is the sum of squares of regression and SST=SSR+SSE">SST=SSR+SSESST=SSR+SSE
THEORY-
Curve fitting is the process of construction of a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and the parameter values, etc. It is highly effective in the mathematical modeling of some natural processes.
1 What does popt and pcov mean?
" popt " is an array that stores the values of the coefficients that are being passed in a given function.
" pcov " is a two-dimensional array that stores the values of the estimated covariance of popt i.e the coefficients.
2 What does np.array(temperature) do?
The above command is used for passing the vales of temperature as a numpy array .
3 What does the * in *popt mean?
" * " in *popt helps us to refer to the coefficients in a given equation
5. What needs to be done in order to make the curve fit perfect?
- By increasing the degree of the curve we can make the best curve fit.
- If we further increase the degree of the curve to 4 then the curve will be more accurate than the cubic polynomial.
- Further increasing the degree of polynomial will increase the calculating complexity and time required, hence 4th order polynomial can be taken as a sufficient curve fit.
4 Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Python Code-
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Curve fit function
def func(t,a,b,c,d):
return a*pow(t,3)+b*t*t+c*t+d
def func1(t,a,b,c,d):
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()
#For Cubic Equation
popt,pcov=curve_fit(func,temperature,cp)
fit_cp=func(np.array(temperature), *popt)
#For Linear Equation
popt1,pcov1=curve_fit(func1,temperature,cp)
fit_cp1=func1(np.array(temperature), *popt1)
#Cubic Equation
plt.figure(1)
plt.plot(temperature,cp,color="blue",Linewidth=3)
plt.plot(temperature,fit_cp,color="red",Linewidth=3)
plt.xlabel('Temperature[k]')
plt.ylabel('Cp')
#Linear Equation
plt.figure(2)
plt.plot(temperature,cp,color="blue",Linewidth=3)
plt.plot(temperature,fit_cp1,color="red",Linewidth=3)
plt.xlabel('Temperature[k]')
plt.ylabel('Cp')
plt.xlabel('temperature[k]')
plt.ylabel('Cp')
plt.show()
Code Explanation-
Required Libraries including numpy,scipy.optimize and matplotlib.pyplot are imported
Func and func1 are programmed to accept the values of t, a,b,c and d and to return the value after calculating by using them all in cubic and linear equations respectively
The thermodynamic values file is read using read function, its value is separated using split function and stored in two different matrices called temperature and cp.
popt and pcov values are found out using curve_fit function. Further, the calculated values are stored by calling func function for cubic equations and stored in fit_cp.
popt1 and pcov1 values are found out using curve_fit function. Further, the calculated values are stored by calling func1 function for Linear equations and stored in fit_cp1.
The plot of fit_cp and actual values are plotted on the same graph for the cubic polynomial equation.
The plot of fit_cp1 and actual values are plotted on the same graph for linear equation.
Output-