Project

Curve-Fitting using PYTHON

Curve-Fitting using PYTHON

Objective: To create PYTHON script that performs linear and cubic curve fits to a given data series. To deduce the reliability of the fits and to explore means of attaining a perfect fit.

Background: The scipy module optimize attribute of curve-fit is a means to deduce the coefficients of a defined function that best fits a data series. A functional relationship is defined, and the curve-fit attribute can by called in PYTHON to determine a guess value for the coefficients of the function. These guess values are then zeroed to optimal values by an inbuilt linearizing model which spits out the optimal coefficients that would fit the functional relationship of the given data series.

Method:

  1. A read file function is defined to open the data file and read it on a line by line basis. A for loop was used to iterate through each line and concurrently, a line split command was used to split the data set in each line using the comma operator.
  2. Subsequently, temperature and specific heat string values from the column split are assigned and appended to the variables ‘temperature’ and ‘cp’ as float point numbers.
  3. Next, generic linear and cubic function are defined as separate function with entailed coefficients.
  4. Thereafter, curve_fit attribute of the scipy module was applied to the function and extracted data set to determine a guess value for the optimal coefficients of the functional relationship. The curve_fit command spits out two attributes, ‘popt’ or optimal parameters(coefficients) and ‘pcov’ or the covariance of the parameters.
  5. Subsequently, the attained optimal coefficients are applied to the originally defined functional relationship on a coefficient by coefficient basis using the *popt along with the temperature values on an element basis using the ‘np.array’ command. Thus, a curve fit value for specific heat is computed.
  6. Next, the original data set is plotted along with the curve fit values of the specific heat for comparison.
  7. This is performed for linear and cubic fits.
  8. Next, a means of attaining a perfect fit is employed in the form of a higher order polynomial quartic function. The same steps are repeated to this purpose.
  9. Finally, the associated standard deviation of the coefficients is computed for comparison.

Data and Analysis:

From the figure below, we may infer that a linear fit is a misrepresentation of the relationship between temperature and specific heat. It encompasses very limited values of the data set and is effective only in representing the direct dependency between the two variables.

\"\"

Figure 1: Linear Curve-Fit

\"\"

Figure 2: Cubic Curve-Fit

As depicted in the figure above, we deduce that a cubic fit a good representation of the functional relationship between temperature and specific heat. The cubic curve encompasses all the data within reasonable uncertainty is therefor a good fit.

\"\"

Figure 3: Quartic Fit

A means of attaining a perfect fit would be employ a higher order polynomial function like a quartic function. As can be seen in the figure above, at a glance the improved quartic fit looks no different to the cubic fit, but it greatly differs in the associated variability. Higher order polynomial fits, though better at encompassing the original data set with the apparently perfect fit to original data series, however outside the range of the data set, the higher order polynomial can be quite oscillatory and potentially misleading by magnitudes of error that are prominent from a mathematical point of view. It can be seen from the comparison of the standard deviations below that the quartic function has lower variability in the form of reduced standard deviation is therefor more of a perfect fit outside the range of the visible data set and more effective in restricting the random variability of the curve fit.

\"\"

Finally, though not included in the methodology of the report there are a few ways to address this possibility of high degree of variability outside the data range. To tackle said issues, a means of fit improvement for the cubic function would be to normalize the curve to a mean value of zero and utilizing a higher order quartic function which would be better poised to mimic the transitions or oscillation in magnitude. An alternate and more robust methodology (not employed in this report) could be to utilize split-wise curve fit to individual sections of the original data set and subsequently employing spline smoothness.

CODE:

\"\"\"
      PYTHON for M.E.
       Curve Fitting
  Authored By Amandeep Singh

PURPOSE
To define a script that performes a linear and cubic curve fit for Specific Heat temperature
data set
\"\"\"

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

# Reading Theromocynamic Data 
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]

#defining linear function
def linear(t,a,b):
	return a*t + b

#defining cubic function 
def cubic(t,a,b,c,d):
	return (a*pow(t,3) + b*pow(t,2) + c*t + d)

#Computing the curve fit
temperature, cp = read_file()

#Linear
popt_linear, pcov_linear = curve_fit(linear,temperature,cp)
fit_linear = linear(np.array(temperature),*popt_linear)
#Cubic 
popt_cubic, pcov_cubic = curve_fit(cubic,temperature,cp)
fit_cubic = cubic(np.array(temperature),*popt_cubic)

#Plotting the curves, LINEAR
plt.figure(1)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature, fit_linear,color=\"red\",linewidth=3)
plt.legend([\'Data\',\'Curve Fit\'])
plt.xlabel(\'Temperature [K]\')
plt.ylabel(\'Specific Heat Cp [J/kg-K]\')
plt.grid()
plt.show()

#Plotting the curves, CUBIC
plt.figure(2)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature, fit_cubic,color=\"red\",linewidth=3)
plt.legend([\'Data\',\'Curve Fit\'])
plt.xlabel(\'Temperature [K]\')
plt.ylabel(\'Specific Heat Cp [J/kg-K]\')
plt.grid()
plt.show()

#Improving the Curve Fit
#Higher order quartic function
def quartic(t,a,b,c,d,e):
	return (a*pow(t,4) + b*pow(t,3) + c*pow(t,2) + d*t + e )

#Computing curve_fit
popt_quartic, pcov_quartic = curve_fit(quartic,temperature,cp)
fit_quartic = quartic(np.array(temperature),*popt_quartic)
#Plotting the Improved Quartic Fit
plt.figure(3)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature, fit_cubic,color=\"red\",linewidth=3)
plt.title(\'Improved Quartic Fit\')
plt.legend([\'Data\',\'Curve Fit\'])
plt.xlabel(\'Temperature [K]\')
plt.ylabel(\'Specific Heat Cp [J/kg-K]\')
plt.grid()
plt.show()

#Computing Standard Deviation
print(\'Comparing Standard Deviations of the Coefficients\')
print(\'-------------------------\')
#Linear
std_linear = np.sqrt(np.diag(pcov_linear))
print(\'The Standard Deviation of Coefficients for Linear Curve\')
print(std_linear)
print(\'-----------------------------------\')
#Cubic
std_cubic = np.sqrt(np.diag(pcov_cubic))
print(\'The Standard Deviation of Coefficients for Cubic Curve\')
print(std_cubic)
print(\'---------------------------------------------------\')
#Quartic
std_quartic = np.sqrt(np.diag(pcov_quartic))
print(\'The Standard Deviation of Coefficients for Quartic Curve\')
print(std_quartic)
print(\'------------------------------------------------------\')
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.