Project

Curve Fitting using Python

Objective: To write a program to perform curve fitting using a Cp vs Temperature data file.

Program:

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

def fn_linear(t,a,b):                                        #linear 
	return a*t+b
	
def fn_cubic(t,a,b,c,d):                                     #cubic                 
	return a*pow(t,3)+b*pow(t,2)+c*t+d
	
def read_file():									         #reading data 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]


temperature,cp = read_file()

popt, pcov =curve_fit (fn_linear,temperature,cp)              #linear
fit_cp_linear = fn_linear(np.array(temperature),*popt)

popt, pcov =curve_fit (fn_cubic,temperature,cp)				  #quadratic
fit_cp_cubic = fn_cubic(np.array(temperature),*popt)

plt.plot (temperature,cp,\'r\')								  #linear
plt.plot (temperature,fit_cp_linear,\'b\')
plt.show()

plt.plot (temperature,cp,\'r\')								  #cubic
plt.plot (temperature,fit_cp_cubic,\'b\')
plt.show()

plt.plot (temperature,cp,\'r\')                                 #linear multiples lines
n= 400
fit_cp_mult = np.zeros(len(temperature))
for i in range (0,int(len(temperature)/n)):
	T1 = temperature[n*i:n*(i+1)]
	popt, pcov =curve_fit (fn_linear,T1,cp[n*i:n*(i+1)])
	fit_cp_mult[n*i:n*(i+1)] = fn_linear(np.array(T1),*popt)            
	plt.figure(1)
	plt.plot (T1,fit_cp_mult[n*i:n*(i+1)],\'b\')
plt.show()

#--------------------ERRORS-----------------
MEAN = np.mean(cp)

ERROR1 = np.array (cp) - np.array (fit_cp_linear)                  #error for linear
ERROR_SQ1=np.square(ERROR1)
SSE1 = sum (ERROR_SQ1)
SSR1 = [x - MEAN for x in fit_cp_linear]
SSR_SQ1 =np.square(SSR1)
SSRR1 = sum (SSR_SQ1)
R_SQ1 = 100*SSRR1/(SSRR1+SSE1)
RMSE1 = pow((SSE1/3200),0.5)
print (R_SQ1,\'...R_SQ linear\')
print (RMSE1,\'...RMSE linear\')
print (\'------------------------------------\')

ERROR2 = np.array (cp) - np.array (fit_cp_cubic)                  #error for cubic
ERROR_SQ2=np.square(ERROR2)
SSE2 = sum (ERROR_SQ2)
SSR2 = [x - MEAN for x in fit_cp_cubic]
SSR_SQ2 =np.square(SSR2)
SSRR2 = sum (SSR_SQ2)
R_SQ2 = 100*SSRR2/(SSRR2+SSE2)
RMSE2 = pow((SSE2/3200),0.5)
print (R_SQ2,\'...R_SQ cubic\')
print (RMSE2,\'...RMSE cubic\')
print (\'------------------------------------\')

ERROR3 = np.array (cp) - np.array (fit_cp_mult)                  #error for multiple lines
ERROR_SQ3=np.square(ERROR3)
SSE3 = sum (ERROR_SQ3)
SSR3 = [x - MEAN for x in fit_cp_mult]
SSR_SQ3 =np.square(SSR3)
SSRR3 = sum (SSR_SQ3)
R_SQ3 = 100*SSRR3/(SSRR3+SSE3)
RMSE3 = pow((SSE3/3200),0.5)
print (R_SQ3,\'...R_SQ multiple line\')
print (RMSE3,\'...RMSE multiple line\')

Procedure:

1. Defining functions:

  • math and matplotlib.pyplot were imported for using mathematical functions and plotting. numpy was imported to do mathematical operations on arrays and curve_fit was imported to fit the given points according to the specified equation.
  • A linear function (`a*t+b`) and a cubic function (`a*t^3+b*t^2+c*t+d`) was defined. The given data set will be plotted according to these equations.
  • Another function (read_file) was defined to read values from the data file. Two separate arrays for the two parameters (temperature and Cp) were formed. \'open\' function was used to read the values from the file and values of temperature and Cp were appended to the arrays previously formed using a loop.

2. Plotting curves:

  • The \'read_file\' function was called to input all temperature and Cp values in their respective arrays.
  • \'curve_fit\' command is used to plot the curve using the defined functions and the temperature and Cp arrays as the input. The optimal values of the coefficients of the defined curve equations are stored in \'popt\' as an array.\'pcov\' stores the values of covariance of the coefficients in \'popt\' in the form of a 2D array.
  • The new Cp array for the curve is obtained by using the temperature and calculated coefficients as input in the defined function.\'np.array(temperature)\' gives the data points of temperature as an array and \'*popt\' gives the values of coefficients of the defined function.
  • The above-mentioned process for curve plotting was repeated for both linear and cubic functions. The fitted curve for both the cases is plotted along with the curve formed by original Cp and temperature values for comparison.
  • In order to form a better fit, a third curve was plotted by using a linear function and splitting the data set into multiple parts. This was done by forming a loop and then repeating the curve fitting process for only 400 data points at a time. Thus, a curve represented by eight linear lines was formed.

3. Calculating errors:

  • To check how good the curve fit given by the program is, values root mean square error(RMSE) and `R^2` were calculated.
  • RMSE is a measure of the average deviation of the Cp from the data file values.
  • The `R^2` value indicates the percentage of variability in Cp that is explained by the model.
  • The formulas to calculate these values are as follows:
    • `RMSE = sqrt((SSE)/n)` where \'SSE\' is the sum of squared errors and \'n\' is the number of data points
    • `R^2=(SSR)/(SST)` where \'SSR\' is the sum of squares of regression and `SST=SSR+SSE`

Results:

  • Three curve fits (blue curve) were plotted along with the original curve (red curve) for comparison as shown below. It was observed that the higher the degree of the polynomial used for curve fit better the accuracy of the curve was. Alternatively, lower degree polynomials can be split into multiple parts to better fit the curve. In the three curves plotted below best fit was observed for the linear curve split into multiple(8 in this case) parts.
  • The values of RMSE and `R^2` were calculated for each of the curves as shown below. It was observed that the value of RMSE was lowest for the curve with multiple lines followed by the cubic curve and the linear curve had the highest RMSE value. The `R^2` value was found to be the highest for the curve with multiple lines followed by the cubic curve.

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.