Challenge

Curve fitting (PYTHON)

Curve fitting (Python)

1. OBJECTIVES

The program should achieve the following objectives:

  1. Answer the questions
  2. Coding to fit a linear and cubic polynomial for the given Temperature v/s Cp data.
  3. Plotting the linear and cubic fit curves along with the raw data points.

2. THEORY

  • Curve fitting is the way we model or represent a data spread by assigning a ‘best fit‘ function (curve) along the entire range. Ideally, it will capture the trend in the data and allow us to make predictions of how the data series will behave in the future.

    It is process of manipulating the free variables to try and make the equations reproduce the known curve as closely as possible.
    If you know the underlying equations are correct, then this may be quite a reasonable way of identifying the value of the free variables. If the underlying equations are not correct, it will produce a solution which apparently fits the data quite well, but is completely bogus. For this reason, it is only valid in situations where you know the equations are correct. Often, but not always, this is the case.
    Because "curve fitting" can make totally incorrect sets of equations superficially look correct, it is often used as a pejorative term indicating the underlying equations are wrong. Incorrect use of curve fitting can be detected by checking the validity of solutions which are outside the range of data used to curve fit - the solutions don't extrapolate properly.

Questions:

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.
  • The “pcov” variavle contains the covariance matrix, which indicated the uncertainties and correlations between parameters. It is a two dimensional array that stores the values of the estimated covariance of popt (i.e. the coefficients). This is mostly useful when the data has uncertainties.

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

np.array(temperature) compiles the temperature list from the data as an array.

3. What does the * in *popt mean?

* in *popt helps us to refer the coefficient in a given equation.

4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.

LINEAR CURVE FITTING

  • PYTHON PROGRAM
#PROGRAM TO PERFORM CURVE FITTING FOR A LINEAR FUNCTION

#Importing modules
import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit

#Linear curve fit function
def func(t,a,b):
	return a*t+b

#Function to read the thermodynamic data file
def read_file():
	temp = []
	cp = []
	for line in open('data','r'):      #Opening a file and reading the data
		values = line.split(',')       #Splitting the line using comma
		temp.append(float(values[0]))  #Appending or adding data into the temp file
		cp.append(float(values[1]))    #Appending or adding data into the cp file

	return [temp, cp]
		
    

temp,cp = read_file()                #Calling the function read_file and storing the values into temp & Cp
popt,pcov = curve_fit(func,temp,cp)  #popt = coefficients (i.e a & b), pcov = estimated covarience of popt
fit_cp = func(np.array(temp),*popt)  #We are passing temp as numpy array


#PLOTTING
plt.plot(temp,cp,color="red",linewidth=3)
plt.plot(temp,fit_cp,color="blue",linewidth=3)
plt.legend(['Actual data','Curve fit data'])
plt.title('LINEAR CURVE FITTING')
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.show()
  • EXPLAINATION OF THE PYTHON PROGRAM
  1. Import necessary modules.
  2. Create linear curve fit function.
  3. Create a function to read the thermodynamic data file.
  4. Then call the function read_file and store the values in temp & Cp variables.
  5. Then store the coefficients values in popt and estimated covariance in popt (i.e. the coefficients) by using curve_fit function of scipy module.
  6. Linear curve fitting is done by the func and outpot values of Cp is stored in fit_cp.
  7. Plotting of actual curves and linear curve.
  • RESULT

CUBIC CURVE FITTING

  • PYTHON PROGRAM
#PROGRAM TO PERFORM CURVE FITTING FOR A CUBIC POLYNOMIAL FUNCTION

#Importing modules
import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit

#Cubic curve fit function
def func(t,a,b,c,d):
	return a*pow(t,3)+b*pow(t,2)+(c*t)+d

#Function to read the thermodynamic data file
def read_file():
	temp = []
	cp = []
	for line in open('data','r'):      #Opening a file and reading the data
		values = line.split(',')       #Splitting the line using comma
		temp.append(float(values[0]))  #Appending or adding data into the temp file
		cp.append(float(values[1]))    #Appending or adding data into the cp file

	return [temp, cp]
		
    

temp,cp = read_file()                #Calling the function read_file and storing the values into temp & Cp
popt,pcov = curve_fit(func,temp,cp)  #popt = coefficients (i.e a, b, c & d ), pcov = estimated covarience of popt
fit_cp = func(np.array(temp),*popt)  #We are passing temp as numpy array


#PLOTTING
plt.plot(temp,cp,color="red",linewidth=3)
plt.plot(temp,fit_cp,color="blue",linewidth=3)
plt.legend(['Actual data','Curve fit data'])
plt.title('CUBIC CURVE FITTING')
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.show()
  • EXPLAINATION OF THE PYTHON PROGRAM
  1. Import necessary modules.
  2. Create cubic curve fit function.
  3. Create a function to read the thermodynamic data file.
  4. Then call the function read_file and store the values in temp & Cp variables.
  5. Then store the coefficients values in popt and estimated covariance in popt (i.e. the coefficients) by using curve_fit function of scipy module.
  6. Linear curve fitting is done by the func and outpot values of Cp is stored in fit_cp.
  7. Plotting of actual curves and cubic curve.
  • RESULT

5. What needs to be done in order to make the curve fit perfect?

In order to make perfect fit, we must consider error estimates as well. Perfect fit means, the curve should fit the original curve without showing any errors (such as centering and scaling errors).

we can make the curve fit perfect in two ways -

  • By increasing the order of polynomial.
  • By splitting the temperature into several parts and performing curve fitting individually.
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.