Challenge

Week 5 - Curve fitting

Aim:

Write program to fit a linear and cubic polynomial for the Cp data. Obtain the best fit for the given data.

Objective:

  • Fit a linear polynomial to the given data.
  • Fit a cubic polynomial to the given data.
  • Fit a best possible fit for the given data.
  • Compare the above cases.

Theory:

Curve fitting is used to obtain a mathematical relation between the parameters from the existing data (may be experimental data)

There can be different possible mathematical models that can represent a data. Model for fitting curve to data depends on the constants present in the model. The best fit is found is if the error between original and derived data is minimised.

For linear fit, the mathematical model used for optimisation is

`C_p=at+b`

For cubic fit, the polynomial used will be in 3rd order and so on.

`C_p=at^3+bt^2+ct+d`

Here least square method is used for optimisation. From the Scipy module, curve fit operation is utilised. Here the inputs are: function to optimise, independent data and dependent data while outputs (Returns) are optimal parameter values (popt) and estimated covariance of the optimal parameter values (pcov)

Program language: Python

Code:

# Fit the data to a curve using polynomial model
# By Manikanteshwara Reddy

import math
import matplotlib.pyplot as plt 
import numpy as np
from scipy.optimize import curve_fit

# Defining the Curve fit equation in polynomial model
def linear(t,a,b):
	return a*t+b
def cubic(t,a,b,c,d):
	return a*pow(t,3)+b*pow(t,2)+c*t+d
def fit(t,a,b,c,d,e):
	return a*pow(t,4)+b*pow(t,3)+c*pow(t,2)+d*t+e

# Read the data file
def read():
	temp = []
	cp = []
	for line in open('data','r'):
		# Seperate data @ ","
		values = line.split(',')
		# Convert the string data to a float (i.e. text to real number)
		temp.append(float(values[0]))
		cp.append(float(values[1]))
	return [temp,cp]
temp, cp = read()
# Optimize the polynomial model accoding to data by calculating the suitable constants(parameters)
popt_l, pcov_l = curve_fit(linear,temp,cp)
popt_c, pcov_c = curve_fit(cubic,temp,cp)
popt_f, pcov_f = curve_fit(fit, temp, cp)
# Calculate the C_p according to the polynomial model with tempeature as the input
# BY numpy array, temperature input is given as array and the output will be an array of C_p from the fitted polynomial model
linear_cp = linear(np.array(temp), *popt_l)
cubic_cp = cubic(np.array(temp), *popt_c)
fit_cp = fit(np.array(temp),*popt_f)
print(popt_l, popt_c, popt_f)

plt.figure(1)
plt.plot (temp,cp, color = "blue",linewidth = 1, label=r'$Actual\ data$')
plt.plot (temp,linear_cp, color = "cyan", linewidth=2, label=r'$Linear \rightarrow C_p = at+b$')
plt.legend(loc = 'best')
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.savefig('Data & Linear fit', facecolor ='c')

plt.figure(2)
plt.plot (temp,cp, color = "blue",linewidth = 1, label=r'$Actual\ data$')
plt.plot (temp,cubic_cp, color = "green", linewidth=2, label=r'$Cubic \rightarrow C_p = at^3 + bt^2 +ct + d$')
plt.legend(loc = 'best')
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.savefig('Data & Cubic fit', facecolor ='c')

plt.figure(3)
plt.plot (temp,cp, color = "blue",linewidth = 1, label=r'$Actual\ data$')
plt.plot(temp,fit_cp, color = "red",linewidth = 2, label=r'$Fit\ curve \rightarrow C_p = at^4 + bt^3 + ct^2 + dt + e$')
plt.legend(loc = 'best')
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.savefig('Data & Fit', facecolor ='c')

The above code is succesfully finished in 3.7 seconds.

  • In the above code, popt and pcov are the returns of the curve fit operation.

popt is a 1D array of the optimal parameter values used for the fitted polynomial

pcov is a 2D array of estimated covariance of popt. The diagonals prrovide the variance of the parameter estimate.

  • temp in the above code is a list and arthematic operations are not supported in this format. To converrt the list into array, np.array(temp) is used and array support the arthematic operations.
  • In above code, wihile calling a fuction arguments are keyed in as *popt. popt is an array and the array size varies with the type of mathematical model used for optimisation. Including a * before the arguments, makes the function recieve arguments from the specified array accordingly. This is generally used when number of arguments are unknown.

Result:

Linear fit:

Cubic fit:

Final fit:

From the above plots for the given data, linear fit deviates more from the original data compared to the other optimised polynomials. The final fit overlaps the original data more signicantly compared to the other models.

It can be observed that increasing the order of the polynomial used for curve fit optimisation traces the original data more efficiently. And also by observing the optimal parameter values for each model, we see that the value of constant 'a' tends to zero which can be understood as the fitted curve matches to the original data curve, the optimised model with zero as its constant value represents its lower degree polynomial model.

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.