# Pendulum Animation
# Install ffmpeg <allows us to create videos>
!apt update -y
!apt install ffmpeg -y
# Import some libraries
import numpy as np
from numpy.linalg import solve
import matplotlib.pyplot as plt
from matplotlib.animation import FFMpegWriter
from matplotlib.patches import Rectangle, Circle
# Define pendulum parameters
g = 9.81 #gravity in m/s^2
L = 1 #Length (m)
# Define our time for the simulation
dt = 0.001
sim_time = 10;
t_vec = np.arange(0,sim_time,dt)
# Define vectors that will hold our state variables over time
theta_vec = np.zeros(len(t_vec))
dtheta_vec = np.zeros(len(t_vec))
#Initial Conditions (one per state variable)
theta_vec[0] = np.pi/4
dtheta_vec[0] = 0;
#Euler Integration
for i in range(1, len(t_vec)):
theta_vec[i] = theta_vec[i-1] + dtheta_vec[i-1]*dt
dtheta_vec[i] = dtheta_vec[i-1] + (-g/L*np.sin(theta_vec[i-1]))*dt
plt.plot(t_vec, theta_vec)
plt.show()
# Set up figure for drawing our pendulum
fig, ax = plt.subplots()
# Create a plot on those axis
p, = ax.plot([], [], color = 'cornflowerblue') #Initializes empty plot
ax.set_xlim([-3, 3])
ax.set_ylim([-3, 3])
ax.axis('equal')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Pendulum Simulation')
video_title = 'simulation'
# Now we want to plot things on the axes
c = Circle((0, 0), radius = 0.1, color = 'cornflowerblue')
ax.add_patch(c) #Add the circle to the patch
#Define information for the video
FPS = 20
sample_rate = int(1/(FPS*dt)) #Samples to skip
dpi = 300
writerObj = FFMpegWriter(fps = FPS)
#Now we need to put the rod and bob in the right place
#Initialize an array containing the positions of the pendulum over time
simulation_size = len(t_vec) #number of time points
x_pendulum_arm = np.zeros(simulation_size)
y_pendulum_arm = np.zeros(simulation_size)
for i in range(0, simulation_size):
x_pendulum_arm[i] = L*np.sin(theta_vec[i])
y_pendulum_arm[i] = -L*np.cos(theta_vec[i])
# Now make a video
with writerObj.saving(fig, video_title+".mp4", dpi):
# Loop through the frames we want to animate
for i in range(0, simulation_size, sample_rate):
#Update the pendulum arm
x_data_points = [0, x_pendulum_arm[i]]
y_data_points = [0, y_pendulum_arm[i]]
p.set_data(x_data_points, y_data_points)
#Update the bob circle
patch_center = x_pendulum_arm[i], y_pendulum_arm[i] #No brackets, just comma, creates a list
c.center = patch_center;
#Update drawing
fig.canvas.draw()
writerObj.grab_frame()
#Imbed the video here
from IPython.display import Video
Video("/work/simulation.mp4", embed = True, width=640, height=480)