Last active
July 21, 2024 05:20
-
-
Save saiccoumar/1211b1f90c2ae00f9927df9b09afdc94 to your computer and use it in GitHub Desktop.
Fitting the tanh function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import numpy as np | |
from scipy.optimize import curve_fit | |
import matplotlib.pyplot as plt | |
import sympy as sp | |
from pandas.plotting import table | |
# Load your data from the CSV file | |
data = pd.read_csv('data.csv') # file for data as comma seperated values | |
print(data.head(10)) | |
# name x and y values from the data correlate that with the values | |
x_data = data['Temperature in Celsius'].values | |
y_data = data['Energy'].values | |
fig, ax = plt.subplots(figsize=(8, 4)) | |
ax.axis('off') | |
table_data = table(ax, data.head(5), loc='center', colWidths=[0.55]*len(data.head(5).columns)) | |
# Save the plot as an image (e.g., PNG) | |
plt.savefig('table_image.png', bbox_inches='tight') | |
# Initial Plot | |
# plt.figure(figsize=(16, 12)) | |
# plt.scatter(x_data, y_data, label="Data") | |
# plt.xlabel("Temperature",fontsize=17) | |
# plt.ylabel("Energy",fontsize=17) | |
# plt.title("Temperature vs Energy",fontsize=22) | |
# plt.show() | |
# hyperbolic tangent (tanh) function | |
def tanh_func(x, a, b, c, d): | |
return a * np.tanh(b * (x + c)) + d | |
# Fit the data to the tanh function | |
# Set initial guess to apparent inflection point | |
initial_guess = [1.0, 1.0, 0.0, 0.0] | |
params, covariance = curve_fit(tanh_func, x_data, y_data, p0=initial_guess) | |
# Extract the parameters | |
a, b, c, d = params | |
# Create a range of x values for the curve change value of "127" to max number or data points i didnt know how to get max size of the data sheet | |
x_fit = np.linspace(min(x_data), max(x_data), 137) | |
# Calculate the y values for the fitted curve | |
y_fit = tanh_func(x_fit, a, b, c, d) | |
# Plot of the data and the fitted curve | |
plt.figure(figsize=(16, 12)) | |
plt.scatter(x_data, y_data, label="Data") | |
plt.plot(x_fit, y_fit, label="Tanh Fit", color= "red") | |
plt.xticks(fontsize=15) | |
plt.yticks(fontsize=15) | |
plt.xlabel("Temperature",fontsize=17) | |
plt.ylabel("Energy",fontsize=17) | |
plt.title("Temperature vs Energy",fontsize=22) | |
# Display the equation | |
equation = f"y = {a:.2f} * tanh({b:.2f} * x + {c:.2f}) + {d:.2f}" | |
print("Equation:", equation) | |
text_x = 8 # x-coordinate | |
text_y = 16 # y-coordinate | |
plt.text(text_x, text_y, equation, fontsize=19, color='red', | |
bbox={'facecolor': 'white', 'alpha': 0.7, 'edgecolor': 'gray'}) | |
# Define the variables and the function | |
x = sp.symbols('x') | |
y = a * sp.tanh(b * (x + c)) + d | |
print("Initialized Equation.") | |
# Calculate the second derivative | |
second_derivative = sp.diff(y, x, 2) | |
print("Solved Second Derivative.") | |
sp.pprint(second_derivative) | |
domain = sp.Interval(-50, 50) | |
inflection_points = sp.solve(second_derivative, x, domain=domain, simplify=False, rational=False) | |
print("Solved Inflection points.") | |
print(inflection_points) | |
inflection_points_numeric = [point.evalf() for point in inflection_points] | |
# Print the inflection point(s) | |
text_x = 8 # x-coordinate | |
text_y = 8 # y-coordinate | |
print("Inflection point(s):", inflection_points_numeric) | |
for inflection_text in inflection_points: | |
inflection_text = "Inflection point at x = " + str(inflection_text) | |
plt.text(text_x, text_y, inflection_text, fontsize=19, color='red', | |
bbox={'facecolor': 'white', 'alpha': 0.7, 'edgecolor': 'gray'}) | |
text_y -= 2 # Adjust vertical position for the next annotation | |
# Show the plot | |
plt.savefig("TempvsEnergyPlot") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment