Challenge

Week 5 - Curve fitting

AIM:

The aim of this study is to analyze thermodynamic data and model the relationship between temperature (T) and specific heat capacity (Cp) using curve fitting techniques implemented in Python.

OBJECTIVE:

  • To fit mathematical models to experimental data for characterizing the T-Cp relationship.

  • To evaluate the fitness characteristics of the fitted curves.

  • To analyze the implications of the curve fitting analysis on understanding thermodynamic behavior.

RESULTS & DISCUSSION:


1.What does popt and pcov mean?

  1. Popt is a numpy array containing the optimized parameters (coefficients) of the curve fit. These parameters are estimated by the curve fitting algorithm to minimize the difference between the fitted curve and the actual data.

  2. Pcov is the estimated covariance of popt. It represents the uncertainty or error associated with each parameter estimate. The diagonal elements of pcov provide the variances of the parameter estimates.

2. What does np.array(temperature) do?

NumPy is a Python library used for working with arrays.It also has functions for working in the domain of linear algebra, fourier transform, and matrices.NumPy stands for Numerical Python.

np.array(temperature) is used for accessing individual elements of temperature array in data

Numpy is imported in python as np.

3. What does the * in *popt mean?

The * in *popt is the unpacking operator in Python. It is used to unpack the elements of the popt array (or tuple) and pass them as individual arguments to a function. In the context of curve fitting, *popt passes the optimized parameters as separate arguments to the curve fitting function.

4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.

MAIN CODE:

import numpy as np

import matplotlib.pyplot as plt

from scipy.optimize import curve_fit

from sklearn.metrics import r2_score

# Define the linear and cubic functions

def linear(t, a, b):

return a * t + b

def cubic(t, a, b, c, d):

return a * (t**3) + b * (t**2) + c * t + d

# Function to read the data 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]

# Read data

temperature, cp = read_file()

# Fit linear polynomial

popt_linear, pcov_linear = curve_fit(linear, temperature, cp)

fit_cp_linear = linear(np.array(temperature), *popt_linear)

# Fit cubic polynomial

popt_cubic, pcov_cubic = curve_fit(cubic, temperature, cp)

fit_cp_cubic = cubic(np.array(temperature), *popt_cubic)

# Calculate residuals

residuals_linear = np.array(cp) - fit_cp_linear

residuals_cubic = np.array(cp) - fit_cp_cubic

# Calculate RSS

rss_linear = np.sum(residuals_linear**2)

rss_cubic = np.sum(residuals_cubic**2)

# Calculate R-squared

r2_linear = r2_score(cp, fit_cp_linear)

r2_cubic = r2_score(cp, fit_cp_cubic)

# Print RSS and R-squared values

print(f"Linear Fit RSS: {rss_linear}, R²: {r2_linear}")

print(f"Cubic Fit RSS: {rss_cubic}, R²: {r2_cubic}")

# Plotting the results

plt.figure(1)

plt.plot(temperature, cp, color='b', linewidth=3)

plt.plot(temperature, fit_cp_linear, color='r', linewidth=3)

plt.title('Linear Polynomial')

plt.legend(['Actual data', 'Curve fit'])

plt.xlabel('Temperature')

plt.ylabel('Cp')

plt.figure(2)

plt.plot(temperature, cp, color='b', linewidth=3)

plt.plot(temperature, fit_cp_cubic, color='g', linewidth=3)

plt.title('Cubic Polynomial')

plt.legend(['Actual data', 'Curve fit'])

plt.xlabel('Temperature')

plt.ylabel('Cp')

plt.figure(3)

plt.plot(temperature, cp, color='b', linewidth=2)

plt.plot(temperature, fit_cp_linear, color='r', linewidth=3)

plt.plot(temperature, fit_cp_cubic, color='g', linewidth=3)

plt.title('Linear vs Cubic')

plt.legend(['Actual data', 'Linear', 'Cubic'])

plt.xlabel('Temperature')

plt.ylabel('Cp')

plt.show()

5. What needs to be done in order to make the curve fit perfect?

To achieve a perfect curve fit, several factors need to be considered and potentially addressed:

  • Model Selection: Choose the most appropriate mathematical model that accurately represents the underlying relationship between the variables. This may involve exploring various model forms (linear, polynomial, exponential, etc.) and selecting the one that best fits the data.

  • Data Quality: Ensure high-quality and precise experimental data. Minimize measurement errors, outliers, and missing values in the dataset.

  • Initial Guesses: Provide reasonable initial guesses for the parameters of the curve fitting model. These initial guesses can significantly impact the convergence and accuracy of the optimization algorithm.

  • Optimization Algorithm: Select an appropriate optimization algorithm for curve fitting. Different algorithms may converge to different solutions, and some may be more suitable for specific types of models or datasets.

  • Parameter Constraints: Apply constraints on the parameters of the model if necessary, to ensure that they remain within physically meaningful ranges.

  • Regularization: Apply regularization techniques to prevent overfitting and improve the generalization ability of the model.

  • Evaluation and Validation: Evaluate the goodness of fit using appropriate metrics (e.g., R^2, RMSE) and validate the model against independent datasets or reference values.

6. Show empirically as to how well your curve has been fit.

Physical Significance:

  • Residual Sum of Squares (RSS): Measures the total deviation of the response values from the fit.

  • R-squared (R²): Indicates the proportion of variance explained by the model.

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.