Challenge

PYTHON PROGRAM TO PERFORM CURVE FIT

PYTHON PROGRAM TO PERFORM CURVE FIT

Objective:

To write a Python program that would perform a curve fit for a range of values of temperature and specific heat capacity of a fluid at constant pressure.

Curve fitting:

Curve fitting is the way we model or represent a data spread by assigning a best fit function (curve) along the entire range.

Ideally, it will capture the trend in the data and allow us to make predictions of how the data series will behave in the future.

Types of curve fitting include:

  • , where we discover a function that is an exact fit to the data points. Since this assumes no measurement error, it has limited applicability to real life scenarios.
  • Smooting is when we find a function that is an approximate fit to the data points, but we give room for error and we allow our actual points to be near, but not necessarily on the line; given the error is minimized overall.

Linear curve fitting, or linear regression, is when the data is fit to a straight line. Although there might be some curve to your data, a straight line provides a reasonable enough fit to make predictions.

Considering the vertical distance from each point to a prospective line as an error, and summing them up over our range, gives us a concrete number that expresses how far from ‘best’ the prospective line is.A line that provides a minimum error can be considered the best straight line.

Since it’s the distance from our points to the line we’re interested in—whether it is positive or negative distance is not relevant—we square the distance in our error calculations. This also allows us to weight greater errors more heavily. So this method is called the least squares approach.

Polynomial curve fitting is when we fit our data to the graph of a polynomial function. The same least squares method can be used to find the polynomial, of a given degree, that has a minimum total error.

popt:

'popt' is a one dimensional array of the best estimates for the output parameter values,in which each entry matches the order in the function definition.

pcov:

'pcov' is the covariance matrix showing the uncertainty and interdependence of each parameter in 'popt'.

'*' function:

The asterisk (star) operator is used in Python with more than one meaning attached to it.

For numeric data types, * is used as multiplication operator.

For sequences such as string, list and tuple, * is a repetition operator.

Single asterisk as used in function declaration allows variable number of arguments passed from calling environment. Inside the function it behaves as a tuple.

The '*' function in '*popt' refers to the operator that stores output parameter values as arrays.

np.array(temperature):

It converts the python list of temperature to a numpy array since operations like pow are allowed on numpy arrays and not python lists.

Numpy array is mostly preferred than creating list because numpy array module is pretty much faster than list execution and convenience.

Best curve fit:

To determine the best fit, we should examine both the graphical and numerical fit results.

The graphical fit results indicate that:

• The fits and residuals for the polynomial equations are all similar, making it difficult to choose the best one.
• The fit and residuals for the single-term exponential equation indicate it is a poor fit overall. Therefore, it is a poor choice and you can remove the exponential fit from the candidates for best fit.
The Numerical fit results indicate that when we can no longer eliminate fits by examining them graphically, we should examine the numerical fit results.
The Curve Fitting app displays two types of numerical fit results:
• Goodness-of-fit statistics - help you determine how well the curve fits the data
• Confidence bounds on the fitted coefficients - determine their accuracy.
We should examine the sum of squares due to error (SSE) and the adjusted R-square statistics to help determine the best fit.
The SSE statistic is the least-squares error of the fit, with a value closer to zero indicating a better fit.
The adjusted R-square statistic is generally the best indicator of the fit quality when you add additional coefficients to your model.
The largest SSE for exp1 indicates it is a poor fit, which you already determined by examining the fit and residuals.
The lowest SSE value is associated with poly6. However, the behavior of this fit beyond the data range makes it a poor choice for extrapolation, so you already rejected this fit by examining the plots with new axis limits.
The next best SSE value is associated with the fifth-degree polynomial fit, poly5, suggesting it might be the best fit.
However, the SSE and adjusted R-square values for the remaining polynomial fits are all very close to each other.

Output:

The following plots show the variation of specific heat of fluid at constant pressure with respect to the temperature correspondingly.

1.Cubic polynomial curve fit

2.Linear curve fit

Results:

While comparing both the plots ,it is evident that the curve with cubic polynomial equation has the better accuracy and coverage of original curve.

Linear curve fitting fails at covering some data points of the actual curve.

Therefore, in order to achieve a better curve fit, a higher order approximation of polynomial is preferred that will suit the actual curve.

Program:

# To perform curve fitting

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


# curve fit function
def func_1(t, a, b, c, d):  # here equation is function of 't',and 'a,b,c,d' are coefficients
    return a * t ** 3 + b * t ** 2 + c * t + d


def func_2(t, a, b):  # here equation is function of 't',and 'a,b' are coefficients
    return a * t + b


# reading data_file
# file contains two columns namely temperature and specific heat
def read_file():  # at constant pressure i.e., cp
    temperature = []
    cp = []
    for line in open('data', 'r'):  # reading each line of file
        temperature.append(float(line.split(',')[0]))  # storing the values of temperature in temperature array
        cp.append(float(line.split(',')[1]))  # storing the values of cp in array cp
    return [temperature, cp]


# Optimizing the curve for cubic polynomial
temperature, cp = read_file()
popt_1, pcov_1 = curve_fit(func_1, temperature, cp)
print(popt_1)
print(pcov_1)
fit_cp_1 = func_1(np.array(temperature), *popt_1)

print('\n')

# Optimizing the curve for linear polynomial
temperature, cp = read_file()
popt_2, pcov_2 = curve_fit(func_2, temperature, cp)
print(popt_2)
print(pcov_2)
fit_cp_2 = func_2(np.array(temperature), *popt_2)

#plotting for cubic polynomial curve fit
plt.plot(temperature, cp, linewidth=3, color='blue')
plt.plot(temperature, fit_cp_1, linewidth=3, color='red')
plt.legend(['actual data', 'curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.title('Cubic polynomial curve fit')
plt.show()
plt.close()

#plotting for linear polynomial curve fit
plt.plot(temperature, cp, linewidth=3, color='blue')
plt.plot(temperature, fit_cp_2, linewidth=3, color='red')
plt.legend(['actual data', 'curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.title('Linear polynomial curve fit')
plt.show()
plt.close()
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.