Project

To perform Curve fit for a given data set using Python

In this project, curve fit is performed for a tabulated list of data containing Specific Heat values at corresponding Temperatures. The data file and the program file needs to be in the same folder (link to data file: https://drive.google.com/file/d/1vWi9Vj3AdQf0gqUK1u9jwS8zg92BHGR0/view?usp=sharing)

Following is the plot for Specific Heat vs Temperature for a specie as per the original data set.

The above curve is not perfectly linear, qudrilateral or cubic. It may therefore be a combination of either of these or perhaps higher order polynomials. The aim of this project is to split the temperature range into two segments and fit different order polynomial to either of the segments. Most optimum point on the temperature scale where it has to be split is estimated by means of minimising the variance corresponding to fitted curve and the original.

In the first case(Case:1) an attempt has been made to fit a linear curve to first segment of the temperature range and a cubic curve to the second segment of the temperature range. In the second case(Case:2) it has been reversed by considering cubic curve for the first segment. Further, in each case the optimum value of temperature(to split the temperature range) has been computed for which combination of curve fit operation results in minimum deviation from the original values.

Below is a Python program to fit a curve for Case:1

"""Curve fitting"""

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

#Reading data from file
def read():
	temp = []
	cp = []

	for i in open('data', 'r'):
		dta = i.split(',')
		temp.append(float(dta[0]))
		cp.append(float(dta[1]))

	return [temp, cp]


#Curve fit function (linear)
def func_1(t, a, b):
	return a*t + b

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




#Assig temperature and specfic heat values to varibles
temp, cp = read()




#Function to Calculate Cp values based on curve fit
def func_pred_cp(n, temp, cp):

	
		pos = temp.index(n)




		#Split temperature range at n and pass to t_1 and t_2
		t_1 = []
		t_2 = []
		cp_1 = []
		cp_2 = []
		
		


		for i in range(0, (pos+1)):
			t_1.append(temp[i])
			cp_1.append(cp[i])
			

		#Assign predicted cp values to cp_1	
		popt, pcov = curve_fit(func_1, t_1, cp_1)
		pred_cp1 = func_1(np.array(t_1), *popt)	

		for j in range((pos+1), (len(temp))):
			t_2.append(temp[j])
			cp_2.append(cp[j])

		#Assign predicted cp values to cp_2	
		popt, pcov = curve_fit(func_3, t_2, cp_2)
		pred_cp2 = func_3(np.array(t_2), *popt)


		#Concatenate cp_1, cp_2 and pass to pred_cp
		pred_cp = []



		for l in pred_cp1:
		
			pred_cp.append(l)

		for k in pred_cp2:
		
			pred_cp.append(k)




		return pred_cp		



#Function to calculate deviation of pred_cp from the original values
def func_err(cp, pred_cp, temp):

	er = 0
	for t in range(0, (len(temp))):
		er = er + pow((cp[t] - pred_cp[t]), 2)

	variance = er/len(temp)
	


	return variance

var = []
temp_range = []
for n in range(750, 950):
	pred_cp = func_pred_cp(n, temp, cp)
	var.append(func_err(cp, pred_cp, temp))
	temp_range.append(n)







#Find minimum variance and standard deviation
min_var = min(var)
min_sd = math.sqrt(min_var)

print (min_var)
print (min_sd)

#Index the temperature for minimum variance
min_temp = var.index(min_var)
opt_temp = temp_range[min_temp]
print (opt_temp)


#Plot the fitted curve corresponding to least deviation(minimum variance)
opt_cp = func_pred_cp(opt_temp, temp, cp)


plt.figure(1)
plt.plot(temp, cp, 'b',label='Real Curve')
plt.plot(temp, opt_cp, 'r',label='Fitted Curve')
plt.xlabel('Temperature(K)')
plt.ylabel('Specific Heat(J/Kg)')
plt.legend(loc='best')
plt.title('Specific Heat vs Temperature')


#Plot variance vs temperature for the range specified
plt.figure(2)
plt.plot(temp_range, var)
plt.xlabel('Temperature(K)')
plt.ylabel('Variance')
plt.title('Measure of error')
plt.show()



In the above program it can be noticed that the iterations has been carried out for a range of temperatures 750K to 950K. This particular range was chosen beacuse it was found that the temprature value at which the temperature scale had to be split was approximately found to be in that range by trial and error subject to minimum deviation from original data set.

Following is the measure of error for the above range of temperatures 750K to 950K

Minimum Variance = 3.016771
Minimum Standard Deviation = 1.736885
The above values correspond to temperature 849K . Therefore it is most suitable to split the temperature at 849K and fit a combination of polynomials to either segments of the temperature bands.

Following is the plot for Curve fit for Case:1

The above pragram can be slightly modified to reverse the sequence of polynomial curves to fit the original data set for Case:2. Here the temperature range is split, for the first segment a cubic curve is fit and for the second, a linear curve is fit. The temperature value at which it is spilt falls approximately in the range 1900K to 2200K subject to minimum deviation from the original data set.

Following is the measure of error for the above range of temperatures 1900K to 2200K

Minimum Variance = 3.259923
Minimum Standard Deviation = 1.805526
The above values correspond to temperature 2084K . Therefore it is most suitable to split the temperature at 2084K and fit a combination of polynomials to either segments of the temperature bands.

Following is the plot for Curve fit for Case:2

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.