Week 5 - Curve fitting
1. Answer to Question Number 1
'popt' and 'pcov' are the output argument of the python's in built function 'curve_fit ' imported from 'scipy' module.
'popt'
- First output argument i.e 'popt' is a 2D array which consists the optimal (best fit) values of coefficients of a polynomial, used for curve fitting process, for which the sum of squared residuals for a given data is minimized. 'popt' can be used to extract the coefficients of a polynomial.
'pcOv'
- Second output argument ie 'pcov' is also a 2D array which gives an estimated values of covariance of coefficients (popt) of a polynomial. The diagonal elements of an array/matrix gives the
value of covariance of a coefficient with itself which is also called as variance of that coefficent. Other non-diagonal elements of the matrix gives the covariance of a coefficient with other coefficient. It is a square matrix (no. of rows = no. of columns). This array/matrix gives the covariance of a coefficient with other coefficient. It is a square matrix (no. of rows = no. of columns). This array/matrix indicates the uncertainties and correlation between the coefficients of a polynomial and it is mostly useful when the data has uncertainties. 'pcov'
can be used to find the standard deviation (square root of the value of diagonal elements) of a given dataset.
2. Answer to Question Number 2
The command 'p.array (temperature)' is used for accessing the individual elements of the temperature array with the help of numpy module. Numpy module/library is imported as 'np'
and used to perform mathematical operations like addition, subtraction, multiplication, division, etc. on each element of an array or between the arrays.
3. Answer to Question Number 3
The star i.e"*' in *popt' unpacks the popt' array so that the optimized coefficients (parameters) values can be accessed from the array "popt'. In other words, * ( means all) aids in referring to all the values stored in the array popt.
4. Answer to Question Number 4
Code to fit a linear and cubic polvnomial to a co data :
#Program to perform curve fitting using linear and cubic polynomial
#Importing the basic libraries/modules from scipy.optimize import curve fit
import math
import matplotlib.pyplot as plt.
import numpy as np
from scipy.optimize import curve_fit
#Function defined for reading the data file containing temperature and cp values
def read_file():
temperature = []
Cp = []
#For loop for reading the file line by line and preparing the data for line in open('data','r'):
values = line.split(',') temperature.append(float (values[0]))
cp.append(float(values[1]))
return[temperature, cp]
#Calling the function read_file to get temperature and cp values
temperature, cp = read_file()
#Performing Curve Fitting using Linear Polynomial
#Function to define the linear polynomial for curve fitting
def linear(T, a, b)
return(a*T+b)
"""
Linear Polynomial
cp =a*T + b
"""
popt1, pcov1 = curve_fit(linear, temperature,cp)
linear_fit_cp = linear (np.array(temperature),*popt1)
#Maximum Percentage Error
error1 = (np.array(np.array(cp) - np.array(linear_fit _cp)))*100/(np.array(cp))
max_error1 = max(error1)
print ('Maximum Percentage Error for Curve Fitting using Linear Polynomial =',max_error1)
print('\n')
#Comparing original data with curve fit using linear polynomial
#Creating an empty figure window
plt. figure(1)
#Creating a plot
plt.plot(temperature, cp, color ='r', linewidth = 2, label = 'Original Data')
plt.plot(temperature, linear_fit_cp, color = 'b', linewidth = 2, label = 'Curve Fit')
#Giving a title to the plot
pit.title(' Comparison of original data set and curve fit using linear polynomial', color = 'k', fontsize = 15, fontweight = 'bold')
# Giving labels to the axes
plt.xlabel('Temperature [K]', fontsize = 12)
plt.ylabel(' Specific Heat [kJ/kg-K]', fontsize = 12)
#Inserting a legend
plt.legend(loc = 'lower right' )
#Inserting the text in a plot
plt. text (200, 1280, 'Polynomial Equation: cp =' + str(popt1[0]) + '*T^3 + '+' ('+str(poopt2[1] + ')' + '*T^2+ ' + str(popt2[3]), color = 'r', fontsize = 8, fontweight = 'bold')
pt. text (200, 1250, 'Maximum Percentage Error =' + str(max error2) + '%' , color = 'r', fontsize = 8, fontweight = 'bold')
# Saving the plot as an image in PNG format plt. savefig(' Curve fit using linear polynomial.png*)
# Making the plots visible
plt. show()
Explanation of the code:-
1. Import the basic modules like math, matploltib, numpy and scipy. The math module is used if any mathematical constants or trigonometric identities are used in the program. The matplotlib module is used for plotting the graphs and numpy module is used to perform mathematical operations on the elements of the array (if any). The scipy module is used to perform curve fit operation by importing it as a optimization function.
2. Defining the function read_file' which is further called for reading the thermodynamic data file line by line using the 'for' loop with line' as a counter variable and storing the data ie temperature and specific heat into two arrays 'temperature' and 'cp' respectively after splitting each line using the command 'line.split (;)' where line is the variable having string format containing the data from each line and comma(,), the delimeter, used as a seperator.
3. The function read _file' is called then to get the arrays 'temperature' and 'cp'.
4. Function named as 'linear' is used to define the linear polynomial which is aim to be fitted to the data.
5. 'popt' (best fit value of coefficients) and pcov (estimated value of covariance of coefficients) are obtained as output arguments by calling the Python's inbuilt function named as curve _fit' and passing the function named as linear and the arrays 'temperature and'co inside the function 'curve _fit' as an input arguments. Then, the new value of cp according to the linear polynomial ie linear_fit _cp' is calculated by calling the function linear' (defined earlier) and passing temperature array element wise using numpy module and all the coefficients of the linear polynomial using "*popt' as an input arguments.
6. Maximum percentage error is calculated by extracting the maximum value from the array 'error' which is calculated using the arrays 'cp' and linear_fit_cp'. It is printed in the command window using the command 'print().
7. A figure of comparison is obtained by plotting the original dataset plot ie (temperature vs cp) and the curve fit plot i.e (temperature vs linear_fit_cp) in a single figure window. Also, the
text like polynomial equation and maximum percentage error is inserted in the figure window using the command 'plt.text'
8. Similarly, the cubic polynomial is fitted to the data except the fourth step in which a cubic polynomial is defined which is further passed as an input argument inside the 'curve _fit' function and used for calculating the new value of cp i.e 'cubic_fit _cp'. Also, a figure of comparison is obtained by plotting the original dataset plot ie (temperature vs cp) and the curve fit plot ie (temperature vscubic_fit_cp) in a single figure window.