Skip to content

Instantly share code, notes, and snippets.

@alexlib
Created May 26, 2024 19:38
Show Gist options
  • Save alexlib/ee66d05f7d6a66ef77af7395cf3d3e8d to your computer and use it in GitHub Desktop.
Save alexlib/ee66d05f7d6a66ef77af7395cf3d3e8d to your computer and use it in GitHub Desktop.
Streamlit app that estimates settling terminal velocity of a sphere
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def drag_coefficient(Re):
"""Calculate the drag coefficient using the empirical correlation."""
if Re < 1:
return 24 / Re
elif Re < 1000:
return 24 / Re * (1 + 0.15 * Re**0.687)
else:
return 24 / Re * (1 + 0.15 * Re**0.687) + 0.42 / (1 + 42500 / Re**1.16)
def terminal_velocity(rho_s, rho_f, g, r, mu):
v_t = 0.01 # Initial guess for terminal velocity
tol = 1e-6 # Tolerance for convergence
max_iter = 1000 # Maximum number of iterations
for _ in range(max_iter):
Re = (rho_f * v_t * 2 * r) / mu
Cd = drag_coefficient(Re)
v_t_new = np.sqrt((8 * r * (rho_s - rho_f) * g) / (3 * Cd * rho_f))
if abs(v_t - v_t_new) < tol:
break
v_t = v_t_new
return v_t, Re, Cd
def equation_of_motion(v, t, rho_s, rho_f, g, r, mu):
Re = (rho_f * v * 2 * r) / mu
Cd = drag_coefficient(Re)
a = (rho_s - rho_f) * g / rho_s - (3 * Cd * rho_f * v**2) / (4 * r * rho_s)
return a
# Streamlit app
st.title('Sphere Settling in a Fluid')
# Input parameters
rho_s = st.number_input('Density of the sphere (kg/m^3)', value=2500.0)
rho_f = st.number_input('Density of the fluid (kg/m^3)', value=1000.0)
d = st.number_input('Diameter of the sphere (m)', value=0.02)
mu = st.number_input('Dynamic viscosity of the fluid (Pa.s)', value=0.001)
g = 9.81
r = d / 2
# Calculate terminal velocity and Reynolds number
v_t, Re, Cd = terminal_velocity(rho_s, rho_f, g, r, mu)
# Calculate time to reach terminal velocity
t = np.linspace(0, 10, 1000)
v0 = 0
velocity = odeint(equation_of_motion, v0, t, args=(rho_s, rho_f, g, r, mu))
# Find the time to reach terminal velocity
time_to_reach_vt = t[np.where(velocity >= 0.99 * v_t)[0][0]]
# Display results
st.write(f"Terminal Velocity: {v_t:.3f} m/s")
st.write(f"Reynolds Number: {Re:.2f}")
st.write(f"Drag Coefficient: {Cd:.3f}")
st.write(f"Time to Reach Terminal Velocity: {time_to_reach_vt:.2f} s")
# Plot velocity vs time
plt.figure(figsize=(10, 6))
plt.plot(t, velocity, label='Velocity of the sphere')
plt.axhline(y=v_t, color='r', linestyle='--', label='Terminal Velocity')
plt.xlabel('Time (s)')
plt.ylabel('Velocity (m/s)')
plt.title('Velocity of a Sphere Settling in a Fluid')
plt.legend()
plt.grid(True)
st.pyplot(plt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment