Challenge

Week 5 - Curve fitting

AIM : To write a code to fit a linear and cubic polynomial for the Cp data by using PYTHON

OBJECTIVE : To Plot the linear and cubic fit curves along with the raw data points and calculate the goodness of fit

EXPLANATION : Curve fitting is the process of constructing a curve or mathematical function that best fits the data points, possibly subjected to constraints. It helps us in understanding the type of relationship between the set of data and helps in predicting the unknown values.

1.What does popt and pcov mean?

'popt' and 'pocv' are the outputs of the function ‘curve_fit’.’popt’ is the array that contains the optimal parameters or the optimum values of the coefficients if the cubic equation . ‘pocv’ is a 2D array that contains the estimated covariance of the parameters in ‘popt’.

2. What does np.array(temperature) do?

‘np.array()’ is used to create a numpy array and the temperature is passed as the data of the array.Numpy array is a central data structure of the numpy library, which is numerical library of python.

3. What does the * in *popt mean?

‘*popt’ is used to expand the list of values stores in the array ‘popt’ into the argments of the function.

PROGRAM :

import math
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'):         #opening a file and reading the data
		values = line.split(',')          #splitting line using comma
		temperature.append(float(values[0]))#appending or adding into the temperature file
		cp.append(float(values[1]))
	return [temperature,cp]
# Main program
temperature,cp = read_file()  #calling the fnction read_file and storing the values into temp & cp
#for cubic equation 
popt,pcov = curve_fit(func,temperature,cp) #popt = coefficient i.e a & b , pov = estimated covarience of popt
fit_cp = func(np.array(temperature),*popt) #we are passing temperature as numpy array
#for linear Equation
popt1,pcov1 = curve_fit(func1,temperature,cp)
fit_cp1 = func1(np.array(temperature),*popt1)
#plotting for both linear and cubic equation
plt.figure(1)
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('Cp')
plt.figure(2)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp1,color="red",linewidth=3)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.show()

PROCEDURE :

  1. Importing 'numpy' as 'np'. numpy is a core library to perform all the scientific calculations in Python.
  2. Importing matlplotlib.pyplot as plt to make python work as Matlab. matplotlib.pyplot is a collection of functions used for various activities such generating figures, generating plots, etc.
  3. Importing the 'curve_fit' function from the package 'spicy.optimize'.
  4. Defining the function 'func' to predict the data variation as a linear and cubic fit.'t', 'a',’b’,’c’ and 'd' are passed as the arguments to the function.
  5. Returning the output of the function in the form of a linear and cubic equation
  6. Defining the function 'read_file' to read the data from the file named 'data'.
  7. Defining an empty array 'temperature' and ’cp’ to store the values of temperature and cp from the file.
  8. Starting a for loop and using it to open the data file and read the contents line by line using the 'line' and 'open' command.
  9. Using the 'line.split' function to split all the lines of the file wherever there is a ',' present between the data. The data is stored in an array 'values' with separate columns for temperature and cp.
  10. Storing all the values of temperature and cp from the first column of the array 'values' after converting them to numbers, to the array 'temperature', using the append command.
  11. Returning the arrays 'temperature' and 'cp' as the output of the for loop and returning the arrays 'temperature' and 'cp' as the output of the function.
  12. Using the 'curve_fit' function to perform curve fitting using the actual data. The arrays 'temperature' and 'cp' containing the actual data are passed as the arguments to the function 'curve_fit'.
  13. The function 'func' for linear fit is passed as the function model to the 'curve_fit' function.
  14. 'popt' and 'pocv' are the outputs of the function 'curve_fit'.
  15. 'popt' is the array that contains the optimal parameters or the optimum values of the coefficients of the linear equation.
  16. 'pcov' is a 2D array that contains the estimated covariance of the parameters in 'popt'.
  17. Calling the function 'func' to calculate the values of the linear function and storing them in the array 'fit_cp'.
  18. 'np.array()' is used to create a numpy array and the temperature is passed as the data of the array.
  19. '*popt' is used to expand the list of values stored in the array 'popt' into the arguments of the function.
  20. Using the 'curve_fit' function to perform curve fitting using the actual data. The arrays 'temperature' and 'cp' containing the actual data are passed as the arguments to the function 'curve_fit'.
  21. The function 'func1' for cubic fit is passed as the function model to the 'curve_fit' function.
  22. 'popt1' and 'pocv1' are the outputs of the function 'curve_fit'.
  23. 'popt1' is the array that contains the optimal parameters or the optimum values of the coefficients of the cubic equation.
  24. 'pcov1' is a 2D array that contains the estimated covariance of the parameters in 'popt1'.
  25. Calling the function 'func1' to calculate the values of the cubic function and storing them in the array 'fit_cp1'.
  26. 'np.array()' is used to create a numpy array and the temperature is passed as the data of the array.
  27. '*popt1' is used to expand the list of values stored in the array 'popt1' into the arguments of the function.
  28. Atlast declaring the figure and plotting the graph between temperature vs cp for both linear and cubic fit.

OUTPUT :

1.linear fit

2.cubic fit

CONCLUSION :

1.The results of linear curve fit are bad as there is a lot of difference between the actual data variation and the variation predicted by linear curve fit. The results of cubic curve fit are good as the variation predicted by cubic curve fit is almost matching the variation of the actual data but there can be a lot of other polynomials as well that match the plot of the actual data.

2.A curve fit can be made perfect by interpolation . curve fitting applies a single function to the entire range of the data while the interpolation method applies a single function for each line of the graph . By increasing the order of the polynomial, the curve fit might match all the data points. But in order to do so, it varies differently between the data points, which can be of less use since it would not explain the actual behaviour or the physics of the data.A best fit might exist. Increasing the order the of the polynomial can result in a function that matches all the data points. But there can be a number of polynomials with different coefficients than can result in the same. The choice of best fit always depend on the explanation of the actual behaviour of the data. The data can be divided in the small portions to achieve a better fit.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.