Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.integrate import odeint
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
|
| 6 |
+
class Pendulum:
|
| 7 |
+
def __init__(self, length, gravity):
|
| 8 |
+
self.L = length
|
| 9 |
+
self.g = gravity
|
| 10 |
+
|
| 11 |
+
def derivatives(self, state, t):
|
| 12 |
+
theta, omega = state
|
| 13 |
+
dydt = [omega, -self.g/self.L * np.sin(theta)]
|
| 14 |
+
return dydt
|
| 15 |
+
|
| 16 |
+
def simulate(self, initial_angle, duration, time_points):
|
| 17 |
+
initial_state = [initial_angle, 0] # angle and angular velocity
|
| 18 |
+
t = np.linspace(0, duration, time_points)
|
| 19 |
+
solution = odeint(self.derivatives, initial_state, t)
|
| 20 |
+
return t, solution
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
st.title("Simple Pendulum Simulator")
|
| 24 |
+
|
| 25 |
+
# User inputs
|
| 26 |
+
length = st.slider("Pendulum Length (m)", 0.1, 5.0, 1.0)
|
| 27 |
+
initial_angle = st.slider("Initial Angle (degrees)", -90.0, 90.0, 45.0)
|
| 28 |
+
|
| 29 |
+
# Convert to radians
|
| 30 |
+
initial_angle_rad = np.deg2rad(initial_angle)
|
| 31 |
+
|
| 32 |
+
# Create and simulate pendulum
|
| 33 |
+
pendulum = Pendulum(length=length, gravity=9.81)
|
| 34 |
+
t, solution = pendulum.simulate(initial_angle_rad, duration=10, time_points=1000)
|
| 35 |
+
|
| 36 |
+
# Plot results
|
| 37 |
+
fig, ax = plt.subplots()
|
| 38 |
+
ax.plot(t, np.rad2deg(solution[:, 0]))
|
| 39 |
+
ax.set_xlabel('Time (s)')
|
| 40 |
+
ax.set_ylabel('Angle (degrees)')
|
| 41 |
+
ax.grid(True)
|
| 42 |
+
st.pyplot(fig)
|
| 43 |
+
|
| 44 |
+
# Display energy conservation
|
| 45 |
+
E_kinetic = 0.5 * length * solution[:, 1]**2
|
| 46 |
+
E_potential = 9.81 * length * (1 - np.cos(solution[:, 0]))
|
| 47 |
+
E_total = E_kinetic + E_potential
|
| 48 |
+
|
| 49 |
+
st.write("### Energy Conservation")
|
| 50 |
+
st.line_chart({"Total Energy": E_total,
|
| 51 |
+
"Kinetic Energy": E_kinetic,
|
| 52 |
+
"Potential Energy": E_potential})
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
main()
|