# Import Libraries:
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from matplotlib.animation import FFMpegWriter
from matplotlib.patches import Circle
!apt update -y
!apt install ffmpeg -y
# Parameters
g = 9.81 # m/s2
m = 1 # kg
dt = 0.001
t_vec = np.arange(0,10,dt)
# Zero Vectors
x_vec = np.zeros(len(t_vec))
dx_vec = np.zeros(len(t_vec))
ddx_vec = np.zeros(len(t_vec))
y_vec = np.zeros(len(t_vec))
dy_vec = np.zeros(len(t_vec))
ddy_vec = np.zeros(len(t_vec))
lamda_vec = np.zeros(len(t_vec))
# Initial Conditions
x_vec[0] = -1 # x position
y_vec[0] = 1 # y position
dx_vec[0] = 0 # x velocity
dy_vec[0] = 0 # y velocity
# Euler's Method
for i in range(1, len(t_vec)):
# X
x_vec[i] = x_vec[i-1] + dx_vec[i-1]*dt
ddx_vec[i-1] = -(x_vec[i-1]*(200*(dx_vec[i-1]**2) + 981))/(50*(4*(x_vec[i-1]**2) + 1))
dx_vec[i] = dx_vec[i-1] + ddx_vec[i-1]*dt
# Y
y_vec[i] = x_vec[i]**2
# Constraints
lamda_vec[i] = (2*m*dx_vec[i-1]**2 + g*m)/(4*dx_vec[i-1]**2 + 1)
# X Position Plot
figure1= plt.plot(t_vec, x_vec)
plt.title('MOD HW 1B: X Position')
plt.show()
# Y Position Plot
figure2 = plt.plot(t_vec, y_vec)
plt.title('MOD HW 1B: Y Position')
plt.show()
# Constraints
figure3 = plt.plot(t_vec, lamda_vec)
plt.title('Homework 1B: Constraints')
plt.show()
# Initialize Figure and Axes
fig, ax = plt.subplots()
p, = ax.plot([], [], color='blue')
ax.axis('equal')
ax.set_xlim([-3, 3])
ax.set_ylim([-3, 3])
# Labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
# Title
ax.set_title('MOD Simulation 1C:')
video_title = "MOD Simulation 1C" # name of the mp4
# Initialize Patch
c = Circle((-1, 1), radius=0.1, color='red')
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
x_func = np.linspace(-2, 2, 2000)
y_func = x_func**2
fig3 = plt.plot(x_func, y_func)
plt.xlim([-2, 2])
plt.ylim([-0.5, 2.5])
plt.show()
simulation_size = len(t_vec)
with writerObj.saving(fig, video_title+".mp4", dpi):
for i in range(0, simulation_size, sample_rate):
p.set_data(x_vec[i], y_vec[i])
patch_center = x_vec[i], y_vec[i]
c.center = patch_center
fig.canvas.draw()
writerObj.grab_frame()
from IPython.display import Video
Video("/work/MOD Simulation 1C.mp4",embed=True, width=640,height=480)