Project

Curve fitting in Python

Curve Fitting:

Objective:Writing code to fit linear and cubic polynomial for the given Cp vs Temperature data file.

Full code:

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

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

def read_file():
	temp=[]
	cp=[]
	for line in open('data','r'):
		values = line.split(',')
		temp.append(float(values[0]))
		cp.append(float(values[1]))
	return [temp,cp]

temperature,cp=read_file()

popt,pcov=curve_fit(func,temperature,cp)

print(pcov)
fit_cp=func(np.array(temperature),*popt)

plt.figure()
plt.plot(temperature,cp,'-b',label='Original data')
plt.plot(temperature,fit_cp,'-r',label='Cubic curve fit data')
plt.xlabel('Temperature')
plt.ylabel('Cp')
plt.legend(loc='best')
plt.savefig('Cubic.png')
plt.show()

Procedure:

1.Importing 'numpy', 'matplotlib' libraries and 'curve_fit' module from 'scipy.optimize' library.

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

2.Defining the polynomial function for curve fiting.

For linear function.

def func(t,a,b):
	return a*t+b

For cubic function.

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

3. Defining function to read the given data file.

def read_file():
	temp=[]
	cp=[]
	for line in open('data','r'):
		values = line.split(',')
		temp.append(float(values[0]))
		cp.append(float(values[1]))
	return [temp,cp]

first two empty array is defined for temperature and Cp values. Then in 'for' loop for each line in the file the data is split in two groups and stored in 'values' variable. These values are stored separately in variables 'temp' and 'cp'.

4. Fuction calling.

temperature,cp=read_file()

5.Using the curve_fit function.

popt,pcov=curve_fit(func,temperature,cp)

Above function takes the defined model function and the data from data file as input. It returns array 'popt' which contains the coefficients of the model funtion.

6.Calculating calculated cp.

fit_cp=func(np.array(temperature),*popt)

To calculate new values of Cp, values of temperature is passed as numpy array and values of coefficient is passed.

7.Ploting graphs.

plt.figure()
plt.plot(temperature,cp,'-b',label='Original data')
plt.plot(temperature,fit_cp,'-r',label='Cubic curve fit data')
plt.xlabel('Temperature')
plt.ylabel('Cp')
plt.legend(loc='best')
plt.savefig('Cubic.png')
plt.show()

Result:

Linear curve fit.

Above result is bad because the calculated curve deviates a lot from the given data.

Cubic curve fit.

Above result is good since the calculated curve fits well with the given data.

Conclusion:

To make the curve fit perfect higher order of polynomial should be taken.

  1. popt and pcov are the valued returned by function 'curve_fit'. 'popt' is an array which contains the optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized. 'pcov' is an 2d array which contains estimated covariance of popt. The diagonals provide the variance of the parameter estimate.
  2. 'np.array(temperature)' passes the values as numpy array to the function.
  3. '*' in '*popt' refers to the coefficents values that is stored in 'popt'.
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.