Project

Curve fit in Python

Introduction:

Curve fitting is the process of constructing a Curve or mathematical function that has the best fit to a series of data points possibly subject to constraints. Curve fitting can involve either interpolation where an exact fit to the data is required, or smoothing in which a \"smooth\" function is constructed that approximately fits the data.

The programme for the Linear and Cubic polynomial Curve Fit:

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

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

def cubfunc(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2)+ c*t + d

#reading thermodyamic 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()
temperature = np.array(temperature)
cp = np.array(cp)

popt1,pcov1 = curve_fit(lin_func,temperature,cp)
popt2,pcov2 = curve_fit(cubfunc,temperature,cp)


fit_cp1 = lin_func(temperature, *popt1)
fit_cp2 = cubfunc(temperature,*popt2)


plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp1,color=\'red\',linewidth=3)
plt.plot(temperature,fit_cp2,color=\'yellow\',linewidth=3)


plt.legend([\'Actual data\',\'Linear fit\',\'cubic fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'Specific Heat\')
plt.show()



# Calculation of residuals: r = data - fit
r1 = cp - lin_func(temperature,*popt1)
r2 = cp - cubfunc(temperature,*popt2)


print(\'Residual1=\',r1)
print(\'Residual2=\',r2)


# determining the standard deviation error of the co efficients
perr1 = np.sqrt(np.diag(pcov1))
perr2 = np.sqrt(np.diag(pcov2))

print(\'perr1 = \',perr1)
print(\'perr2 = \',perr2)

Explanation of the Code:

Importing math for the mathematical calculation, importing numpy to create an array of temperature, importing matplotlib.pyplot for plotting the graph of temperature and specific heat , and from scipy moudule importing curve fit to perform the curve fit.

Linear equation and cubic equation are defined in the function so that they can be called later in the main program while performing the curve fitting .

For the thermodynamic data available with us we use “open” command to open the file following with the letter “r” to get in the read mode. As there is huge amount of data in our file , we use for loop to read every line and split the data with the comma “ , “ in the lines of the data using split function.

Temperature and specific heat are stored in separate arrays , using numpy module

Curve fit is done which returns two arrays “popt” and “pcov” , popt is the Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized .

Where as the “pcov” means The estimated covariance of popt. The diagonals provide the variance of the parameter estimate .

In passing the command popt in curve fit we have used it as the *popt , that is because the * is the pointer operator and points out all the elemnts in that array .

The predicted cp is calculated as the fit_cp for the linear and the cubic function .

The graph is plotted using the predicted cp of the polynomals, and compared with the original data set.

The output of the above code is :

\"\"

\"\"

Conclusion:

By using the higher order polynomials we minimize the error , as we can see in the above graph that cubic fit fits the curve best than the linear fit.

We can also make the curve best fit using the different polynomials for different tmepeerature range , or splitting the data into certain number of sets ( int his case I have splitted into 4)

And calculating the specific heat for those temperature range,

The programme for the different polynomial for different range of temperature:

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

#curve fit function
def quadfunc(t,a,b,c):
	return a*pow(t,2) + b*t + c

def cubfunc(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2)+ c*t + d

def f4(t,a,b,c,d,e):
	return a*pow(t,4) + b*pow(t,3) + c*pow(t,2) + d*t + e

def f5(t,a,b,c,d,e,f):
	return a*pow(t,5) + b*pow(t,4) + c*pow(t,3) + d*pow(t,2) + e*t + f

#reading thermodyamic 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()
t1 = np.array(temperature[0:800])
t2 = np.array(temperature[800:1600])
t3 = np.array(temperature[1600:2400])
t4 = np.array(temperature[2400:3200])


popt1,pcov1 = curve_fit(quadfunc,t1,cp[0:800])
popt2,pcov2 = curve_fit(cubfunc,t2,cp[800:1600])
popt3,pcov3 = curve_fit(f4,t3,cp[1600:2400])
popt4,pcov4 = curve_fit(f5,t4,cp[2400:3200])

fit_cp1 = quadfunc(t1, *popt1)
fit_cp2 = cubfunc(t2,*popt2)
fit_cp3 = f4(t3,*popt3)
fit_cp4 = f5(t4,*popt4)

plt.plot(temperature,cp,color=\'blue\',linewidth=5)
plt.plot(t1,fit_cp1,color=\'red\',linewidth=2)
plt.plot(t2,fit_cp2,color=\'yellow\',linewidth=2)
plt.plot(t3,fit_cp3,color=\'black\',linewidth=2)
plt.plot(t4,fit_cp4,color=\'orange\',linewidth=2)

plt.legend([\'Actual data\',\'quadratic fit\',\'cubic fit\',\'Fourth order fit\',\'Fifth order fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'Specific Heat\')
plt.show()

# Calculation of residuals: r = data - fit
r1 = cp[0:800] - quadfunc(t1,*popt1)
r2 = cp[800:1600] - cubfunc(t2,*popt2)
r3 = cp[1600:2400] - f4(t3,*popt3)
r4 = cp[2400:3200] - f5(t4,*popt4)

print(\'Residual1=\',r1)
print(\'Residual2=\',r2)
print(\'Residual3=\',r3)
print(\'Residual4=\',r4)


# determining the standard deviation error of the co efficinets
perr1 = np.sqrt(np.diag(pcov1))
perr2 = np.sqrt(np.diag(pcov2))
perr3 = np.sqrt(np.diag(pcov3))
perr4 = np.sqrt(np.diag(pcov4))

print(\'perr1 = \',perr1)
print(\'perr2 = \',perr2)
print(\'perr3 = \',perr3)
print(\'perr4 = \',perr4)




The output for the above function:

\"\"

As we can see from the above programme splitting the entire data into some would fits the curve better rather than using one higher order polynomial for the entire data.

And for the lesser values of temperature we can observe that lower order polynomials fits , and as the data size and the values increases the order of polynomial should increase to get the best 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.