Week 5 - Curve fitting
AIM :- Program to perform curve fitting in python.
Curve fitting :- Curve fitting is one of the most powerful and most widely used analysis tools. Curve fitting examines the relationship between one or more independent variables and a response dependent variable, with the goal of defining a "best fit" model of the relationship.
It can be achieved in python by using scipy library.
Scipy is the scientific computing module of Python providing in-built functions on a lot of well-known Mathematical functions. The scipy.optimize package equips us with multiple optimization procedures.
- What does popt and pcov mean?
a.) popt – ‘popt’ is a one dimensional array that stores the values of the coefficients of the defined function.
b.) pcov – ‘pcov’ is the covariance matrix showing the uncertainty and interdependence of each parameter(corfficients) in popt.
- What does np.array(temperature) do?
It passes the values of temperature from given dataset as a numpy array.
- What does the * in *popt mean?
Instead of passing each coefficients we use ‘popt’ (have values of coefficients) and ‘*’ refers these values.
- Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
a.) Linear curve-fit for the Cp data
""" program to perform linear curve_fit"""
import numpy as np # importing numpy library to compute & manipulate multidimensional arrays
import matplotlib.pyplot as plt # importing matplotlib library to create curves
from scipy.optimize import curve_fit # importing curve_fit library from scipy module to perform curve fit
# Curve_fit function defining a function that relates temperature & cp data linearliy
def func(t, a, b):
return(a*t +b)
# Reading thermodynamic data file defining a function to read & extract the req. data from the given file
def read_file():
temperature = [] # Empty array to store the temperature data.
cp = [] # Empty array to store the specific heat(cp) data.
for line in open('data', 'r'): # open the file & read the data.
values = line.split(',') # split the line at ',' in the given data file.
temperature.append(float(values[0])) # In the give data file first value is of temperature, therefore we extract this string values & convert it to float ,store them in the empty array of temperature, & jump to the next line.
cp.append(float(values[1])) # In the give data file second value is of specific_heat, therefore we extract this string values & convert it to float ,store them in the empty array of cp, & jump to the next line.
return[temperature,cp]
# Main Program
temperature, cp = read_file() # read the temp. & cp arrays
popt, pcov = curve_fit(func, temperature, cp) # find the values of coefficients(popt) & estimate correspnding covariance(pcov) by using the temperature &cp values and relation between them
fit_cp = func(np.array(temperature), *popt) # passing temperature as numpy array
#plots plot the required curves, by defining proper labels & legends
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() # show the generated plots
Output :-
fig. - Curve-fit for linear polynomial
As it can be seen that there is large difference in both the actual curve & curve fit. Therefore it is a bad curve-fit.
b.) cubic curve-fit for the Cp data :-
""" program to perform cubic polynomial curve_fit"""
import numpy as np # importing numpy library to compute & manipulate multidimensional arrays
import matplotlib.pyplot as plt # importing matplotlib library to create curves
from scipy.optimize import curve_fit # importing curve_fit library from scipy module to perform curve fit
# Curve_fit function defining a cubic function that relates temperature & cp.
def func(t, a, b, c, d):
return(a*pow(t,3) +b*pow(t,2) +c*t +d)
# Reading thermodynamic data file defining a function to read & extract the req. data from the given file
def read_file():
temperature = [] # Empty array to store the temperature data.
cp = [] # Empty array to store the specific heat(cp) data.
for line in open('data', 'r'): # open the file & read the data.
values = line.split(',') # split the line at ',' in the given data file.
temperature.append(float(values[0])) # In the give data file first value is of temperature, therefore we extract this string values & convert it to float ,store them in the empty array of temperature, & jump to the next line.
cp.append(float(values[1])) # In the give data file second value is of specific_heat, therefore we extract this string values & convert it to float ,store them in the empty array of cp, & jump to the next line.
return[temperature,cp]
# Main Program
temperature, cp = read_file() # read the temp. & cp arrays
popt, pcov = curve_fit(func, temperature, cp) # find the values of coefficients(popt) & estimate correspnding covariance(pcov) by using the temperature &cp values and relation between them
fit_cp = func(np.array(temperature), *popt) # passing temperature as numpy array
#plots plot the required curves, by defining proper labels & legends
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() # show the generated plots
Output :-
fig:- Curve-fit for cubic polynomial
As the polynomial becomes cubic from linear the curve fit matches the actual curve upto some extent , but not yet completely. Therefore this curve-fit is better than linear curve-fit but yet not perfect.
- What needs to be done in order to make the curve fit perfect?
In order to make curve-fit perfect, either we can use higher order polynomial function or by breaking the temperature in two or more ranges.
PERFECT CURVE-FIT BY USING HIGHER ORDER POLYNOMIAL-
On increasing the degree of polynomial, curve-fit approaches to perfect fit and finally at degree 10, we have perfect fit.
""" program to perform higher order polynomial curve_fit"""
import numpy as np # importing numpy library to compute & manipulate multidimensional arrays
import matplotlib.pyplot as plt # importing matplotlib library to create curves
from scipy.optimize import curve_fit # importing curve_fit library from scipy module to perform curve fit
# Curve_fit function defining a cubic function that relates temperature & cp.
def func(t, a, b, c, d, e, f, g, h, i, j, k,l):
return(a*pow(t,11) + b*pow(t,10) + c*pow(t,9) + d*pow(t,8) + e*pow(t,7) + f*pow(t,6) + g*pow(t,5) + h*pow(t,4) + i*pow(t,3) + j*pow(t,2) + k*t + l)
# Reading thermodynamic data file defining a function to read & extract the req. data from the given file
def read_file():
temperature = [] # Empty array to store the temperature data.
cp = [] # Empty array to store the specific heat(cp) data.
for line in open('data', 'r'): # open the file & read the data.
values = line.split(',') # split the line at ',' in the given data file.
temperature.append(float(values[0])) # In the give data file first value is of temperature, therefore we extract this string values & convert it to float ,store them in the empty array of temperature, & jump to the next line.
cp.append(float(values[1])) # In the give data file second value is of specific_heat, therefore we extract this string values & convert it to float ,store them in the empty array of cp, & jump to the next line.
return[temperature,cp]
# Main Program
temperature, cp = read_file() # read the temp. & cp arrays
popt, pcov = curve_fit(func, temperature, cp) # find the values of coefficients(popt) & estimate correspnding covariance(pcov) by using the temperature &cp values and relation between them
fit_cp = func(np.array(temperature), *popt) # passing temperature as numpy array
#plots plot the required curves, by defining proper labels & legends
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() # show the generated plots
Output :-
fig. - 10th order polynomial curve-fit
As it can be seen that both the actual curve & curve-fit curve overlaps. Hence it is a perfect fit.