CURVE FIT USING PYTHON
1.AIM :
PROGRAM TO FIT LINEAR AND CUBIC POLYNOMIAL FOR THE GIVEN SPECIFIC HEAT(Cp) DATA USING PYTHON
2.THEORY AND GOVERNING EQUATIONS :
Curve fitting
Curve fitting is the process of constructing a curve which very closely resembles the variation of mathematical function of the used set of data points. By curve fitting one can easily construct a mathematical relation between dependent and independent variable.
How to improve the fit of curve
So to find a curve which closely resembles the curve of the original database we have to eliminate the error between the original dataset points and predicted dataset points.
Assume the original data points to be (x1,y1) , (x2,y2) , (x3,y3) , ... (xn,yn) and assume the mathematical function for best to be y = f(x). The error at individual point will be difference in y co-ordinate values.
`"Error" = | y ( i ) − "value of f(x) at x(i)" | = | y ( i ) − f ( x ( i ) ) |`
There are basically two methods to minimize this error and get the best fit.
- Increase the degree of the polynomial
- Using the split-wise method (i.e. divide the data points in segments)
How to evaluate a curve fit
To evaluate a fit the factor R-square will help us, it will measure the goodness of fit and check how well the equation satisfies the set of data points.
R-square:- This quantity measures how closely the fit resembles the variation of the data, it is the correlation between the dataset values and the predicted values.
R-square ranges from a value of 0 to 1, higher the value of R-square the better is the fit.
`R^2 = (S S R )/(S S T)`
where
1) `S S T = S S R + S S E`
2) SSE is Sum of squared errors
To remove the modulus sign we square the error term and if we add the errors for all the points we get
`SSE = sum_(i=0)^n [ y ( i ) − f ( x (i )) ] ^2`
3) SSR is sum of squares of the regression
It is the square of the difference between the value of the assumed function at a given point and the arithmetic mean of the given dataset.
`S S R = sum_(i=0)^n [(f ( x ( i ) ) − M e a n ]^ 2`
Here in this work, the curve fit is performed for a linear polynomial and a cubic polynomial and further the curve fit is evaluated by calculating the value of factor R-square.
3.OBJECTIVES :
- Write a program to curve fit for a linear and cubic polynomial for the given Cp data.
- Plot the linear and cubic curve fit along with original dataset points.
- To evaluate the curve fit.
4.PYHTON PROGRAM :
Program to fit a linear polynomial for the Cp data
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Curve fit function
def func(t,a,b):
return a*t + b #linear Polynomial
#Reading thermodynamic data file
def read_file():
temperature=[]
cp=[]
for line in open('data','r'):
values=line.split(',')
temperature.append(float(values[0])) #Here tempearture values are stored from data
cp.append(float(values[1])) #Here cp values are stored from data
return [temperature,cp]
#Main Program
temperature,cp=read_file()
popt,pcov=curve_fit(func,temperature,cp) #Best valueof coefficients are obtained
fit_cp=func(np.array(temperature),*popt) #Curve fitting
#Plotting
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp,color="red",linewidth=3)
plt.legend(['Actual Data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.show()
#evluation of fit
ssr=0
sse=0
#calculating mean of cp dataset using sum and len functions
meancp = sum(cp)/len(cp)
#calculating ssr
for i in range(0,len(cp)):
b = pow((fit_cp[i]-meancp),2)
ssr=ssr+b
#calculating sse
for j in range(0,len(cp)):
c = pow((cp[j]-fit_cp[j]),2) #looping so as to generate value of c for every value of cp and fit_cp
sse = sse+c #adding all values of c
sst = ssr+sse
R = ssr/sst
print('R-square = ',R)
Program to fit a cubic polynomial for the Cp data
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Curve fit function
def func(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d #cubic Polynomial
#Reading thermodynamic data file
def read_file():
temperature=[]
cp=[]
for line in open('data','r'):
values=line.split(',')
temperature.append(float(values[0])) #Here tempearture values are stored from data
cp.append(float(values[1])) #Here cp values are stored from data
return [temperature,cp]
#Main Program
temperature,cp=read_file()
popt,pcov=curve_fit(func,temperature,cp) #Best value of coefficients are obtained
fit_cp=func(np.array(temperature),*popt) #Curve fitting
#Plotting
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp,color="red",linewidth=3)
plt.legend(['Actual Data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.show()
#evluation of fit
ssr=0
sse=0
#calculating mean of cp dataset using sum and len functions
meancp = sum(cp)/len(cp)
#calculating ssr
for i in range(0,len(cp)):
b = pow((fit_cp[i]-meancp),2)
ssr=ssr+b
#calculating sse
for j in range(0,len(cp)):
c = pow((cp[j]-fit_cp[j]),2) #looping so as to generate value of c for every value of cp and fit_cp
sse = sse+c #adding all values of c
sst = ssr+sse
R = ssr/sst
print('R-square = ',R)
Explanation:
- Initially the required modules (matplotlib, numpy and scipy) are imported.
- then a function is defined which returns the value of assumed function, i.e. in case of linear fit the function to be solved is `C_p=aT + b` and in case of cubic fit the function sloved is `C_p=aT^3+bT^2+cT+d`.
- Then the data from the thermodynamic data file is loaded, by using open() function used under the user defined function 'read_file()'.
- The temperature and specific heat values in the dta file are separated by a ',' so using this character the values are split.
- The splitted values are appended to the temperature and cp varible using the append() function.
- For curve fitting, 'popt' and 'pcov' are used as for storing parameters obtained by 'curve_fit' function command which takes input as the required function(linear or cubic) ,temperature and Cp. From the output of curve_fit() function, we obtain the coefficients of polynomial.
- Then, an another variable named 'fit_cp' stores the new values of Cp calculated by using temperature array.
- Plots of both given dataset and predicted dataset values are made to compare the fitness of both the linear and cubic polynomial curves.
- next the fitness of the curve fit is evaluated using R-square method and the value of R-square is displayed.
5.RESULTS :
For linear polynomial curve fit
R-square value
For cubic polynomial curve fit
R-square value
It can be seen from the 2 graphs that the curve fit is better in case of cubic polynomial and from the value of R-square too it can be stated that increased the degree of assumed polynomial gives a better curve fit.
Answers to some questions
1. What does popt and pcov mean?
Answer- popt is an array which stores the best value of coefficients of polynomials taken into consideration.
pcov is a multidimensional array whose diagonal contains the variance of 'popt' such that we can extract the one standard deviation error by taking the square root of these elements, the order of matrix depends on degree of polynomial i.e. if polynomial is linear then the matrix is 2-D and if polynomial is quadratic then the matrix is 3-D.
2. What does np.array(temperature) do?
Answer- It converts the temperature list into a numpy array, in program after conversion this value is passed to function.
3. What does the * in *popt mean?
Answer- popt stores all the value for polynomial coefficients and the *(star) refers to address of all the coefficients.
4.What needs to be done in order to make the curve fit perfect?
Answer- Perfect fit means, the curve should fit the original curve without
showing any errors, so in order to make the curve fit perfect the error estimates should be minimized. So to get a perfect fit, either the degree of assumed polynomial can be increased of the dataset points (here temperature) can be divided into segments and curve fit can be performed for each segment individually.
The curve fit can also be evaluated using the R-square method, which can how good the curve fit is.
6.CONCLUSION :
- Curve fit for Linear and cubic polynomial was performed successfully.
- As we increase the degree of the polynomial, the curve fit becomes better.
- The factor R-square can be used to evaluate a curve fit.
7.REFERENCES :
https://skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860