Curve Fit ||| Python program
OBJECTIVE:
To perform a curve fit.
CURVE FIT:
Curve fitting is the process of constructing a curve or mathematical function which fits the best to the real series of data.
The curve fit describes how the data changes mathematically.
CODE:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
temp = []
cp = []
# Calculating the number of data points
text_file = open('data','r')
for line in text_file:
v=line.split(',')
temp.append(float(v[0]))
cp.append(float(v[1]))
text_file.close()
def sub_lst(lst,sub_size): # splitting the list
for i in range(0,len(lst),sub_size):
yield lst[i:i+sub_size]
T = list(sub_lst(temp,800))
k = T[0]
k = list(sub_lst(k,400))
#print(len(k))
CP = list(sub_lst(cp,800))
CP_N = CP[0]
CP_N = list(sub_lst(CP_N,400))
# Curve fit function Linear
def lin(a,x,b):
return a*x + b
#linear
popt_i,pcov_i = curve_fit(lin,k[0],CP_N[0])
cp_n1 = lin(np.array(k[0]),*popt_i)
popt_f,pcov_f = curve_fit(lin,k[1],CP_N[1])
cp_n2 = lin(np.array(k[1]),*popt_f)
popt_2,pcov_l2 = curve_fit(lin,T[1],CP[1])
cp_l2 = lin(np.array(T[1]),*popt_2)
popt_3,pcov_l3 = curve_fit(lin,T[2],CP[2])
cp_l3 = lin(np.array(T[2]),*popt_3)
popt_4,pcov_l4 = curve_fit(lin,T[3],CP[3])
cp_l4 = lin(np.array(T[3]),*popt_4)
CP_N = np.concatenate((cp_n1,cp_n2))
CP_L = np.concatenate((CP_N,cp_l2,cp_l3,cp_l4))
#print(len(CP_L))
plt.figure(1)
plt.plot(temp,cp,color='red',linewidth =2)
plt.plot(temp,CP_L,color='green',linewidth =2)
plt.legend(['Original data','curve fit linear'])
plt.xlabel('temperature')
plt.ylabel('CP')
def quad(t,a,b,c):
return a*pow(t,2) + b*t + c
def cubic(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
# reading the 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
#quad
temperature,cp = read_file()
popt_q,pcov_q = curve_fit(quad,temperature,cp)
cp_q = quad(np.array(temperature),*popt_q)
#cubic
temperature,cp = read_file()
popt_c,pcov_c = curve_fit(cubic,temperature,cp)
cp_c = cubic(np.array(temperature),*popt_c)
#Error Linear
error = cp - CP_L
SSE = sum(pow(error,2))
reg =cp - np.mean(CP_L )
SSR= sum(pow(reg,2))
SST= SSE + SSR
R_square = SSR/SST
print('The R square value for linear function is :',R_square)
# Error Quad
error = cp - cp_q
SSE = sum(pow(error,2))
reg =cp - np.mean(cp_q)
SSR= sum(pow(reg,2))
SST= SSE + SSR
R_square = SSR/SST
print('The R square value for quadratic function is :',R_square)
# Error Cubic
error = cp - cp_c
SSE = sum(pow(error,2))
reg =cp - np.mean(cp_c)
SSR= sum(pow(reg,2))
SST= SSE + SSR
R_square = SSR/SST
print('The R square value for cubic function is :',R_square)
# quadratic plot
plt.figure(2)
plt.plot(temperature,cp,color='red',linewidth =2)
plt.plot(temperature,cp_q,color='green',linewidth =2)
plt.legend(['Original data','curve fit quadratic'])
plt.xlabel('temperature')
plt.ylabel('CP')
# cubic plot
plt.figure(3)
plt.plot(temperature,cp,color='red',linewidth =2)
plt.plot(temperature,cp_c,color='orange',linewidth =2)
plt.legend(['Original data','curve fit cubic'])
plt.xlabel('temperature')
plt.ylabel('Cp')
plt.show()
PROCEDURE:
- 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,x,b) ,quadratic function (a*pow(t,2) + b*t + c ) 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.
- The above-mentioned process for curve plotting was repeated for linear, quadratic and cubic functions. The fitted curve for the cases is plotted along with the curve formed by original Cp and temperature values for comparison.
- For the linear function the data has been split so to get a good curve fit.
RESULTS:
Linear Curve Fit
Quadratic Curve Fit
Cubic Curve Fit
CONCLUSION:
- From the above observation it is clear that increasing the order of polynomial the errors also reduces which helps us get a better curve.
- Another way to to improve the fit is by splitting the data, using smaller data range.