!apt update -y
!apt install ffmpeg -y
import numpy as np
import matplotlib.pyplot as plt
import sympy
from matplotlib.animation import FFMpegWriter
from matplotlib.patches import Circle
g = 9.8
m = 1
dt=0.001
t_vec=np.arange(0,10,dt)
x_vec=np.zeros(len(t_vec))
dx_vec=np.zeros(len(t_vec))
y_vec=np.zeros(len(t_vec))
dy_vec=np.zeros(len(t_vec))
lamda_vec=np.zeros(len(t_vec))
x_vec[0]=-1
dx_vec[0]=0
y_vec[0]=1
dy_vec[0]=0
A=np.array([[m, 0, 0], [0, m, 1], [0, 1, 0]])
b=np.array([0, -m*g, 0])
for i in range (1, len(t_vec)):
A[0, 2]=-2*x_vec[i-1]
A[2, 0]=-2*x_vec[i-1]
b[2]=2*dx_vec[i-1]**2
[ddx, ddy, lamda]=np.linalg.solve(A,b)
x_vec[i]=x_vec[i-1] + dx_vec[i-1]*dt
y_vec[i]=x_vec[i-1]**2
lamda_vec[i]=lamda
dx_vec[i]=dx_vec[i-1]+ddx*dt
dy_vec[i]=dy_vec[i-1]+ddy*dt
plt.plot(t_vec,x_vec)
plt.show()
plt.plot(t_vec, y_vec)
plt.show()
plt.plot(t_vec,lamda_vec)
plt.show()
# Set # Setup Figure: Initialize Figure / Axe Handles
fig, ax = plt.subplots() # Initialize Figure and Axes
p, = ax.plot([], [], color='cornflowerblue') # Initialize Empty Plot
ax.axis('equal')
ax.set_xlim([-3, 3]) # X Lim
ax.set_ylim([-3, 3]) # Y Lim
ax.set_xlabel('X') # X Label
ax.set_ylabel('Y') # Y Label
ax.set_title('Simulation:') # Plot Title
video_title = "simulation" # name of the mp4up figure for drawing
# Initialize Patch:
c = Circle((0, 0), radius=0.1, color='cornflowerblue') # Draws a circle of radius 0.1 at (X, Y) location (0, 0)
ax.add_patch(c) # Add the patch to the axes
# Setup Animation Writer:
FPS = 20 # Frames per second for the video
sample_rate = int(1 / (dt * FPS)) # Rate at which we sample the simulation to visualize
dpi = 300 # Quality of the Video
writerObj = FFMpegWriter(fps=FPS) # Video Object
# We need to calculate the cartesian location of the pendulum:
# Initialize Array:
simulation_size = len(t_vec) # We use this alot, so lets store it.
x_pos = np.zeros(simulation_size)
y_pos = np.zeros(simulation_size)
# Find the X and Y trajectories of the pendulum:
for i in range(0, simulation_size):
x_pos[i] = 0 + x_vec[i]
y_pos[i] = 0 + y_vec[i]
with writerObj.saving(fig, video_title+".mp4", dpi):
for i in range (0,simulation_size, sample_rate):
patch_center = x_pos[i], y_pos[i]
c.center=patch_center
fig.canvas.draw()
writerObj.grab_frame()