HW 1 - 755180-MOD-HW1
# This code block installs ffmpeg to your Deepnote Machine
# Allows Deepnote to write MP4
!apt update -y
!apt install ffmpeg -y
Problem 1 - Bead on Wire
Problem 1 - Imports
#HW1 Problem 1
import numpy as np
from numpy.linalg import solve
import matplotlib.pyplot as plt
from matplotlib.animation import FFMpegWriter
from matplotlib.patches import Circle
Problem 1 - Simulation
#Define Constants
g = 9.8
m = 1
#define time
dt = 0.001 # Time Step
sim_time = 10 # Length of Simulation
t_vec = np.arange(0, sim_time, dt)
#Initialize State Vectors
vec_size = len(t_vec)
x_vec = np.zeros(vec_size)
dx_vec = np.zeros(vec_size)
y_vec = np.zeros(vec_size)
dy_vec = np.zeros(vec_size)
lam_vec = np.zeros(vec_size)
#Initial Conditions
x_vec[0] = -1
dx_vec[0] = 0
y_vec[0] = x_vec[0]**2
dy_vec[0] = 2*x_vec[0]*dx_vec[0]
lam_vec[0] = 0
#Lets start simulating some stuff
A = np.array([[m, 0, 2*x_vec[0]], [0, m, -1] , [ 2*x_vec[0], -1, 0]])
B = np.array([0, -m*g, -2*(dx_vec[0] ** 2)])
for i in range(1, vec_size):
#Only Update Top right and bottom left
A[0, 2] = 2*x_vec[i-1]
A[2, 0] = 2*x_vec[i-1]
#Last element of b must be updated
B[2] = -2*(dx_vec[i-1] ** 2)
[ddx, ddy, lam_vec[i]] = np.linalg.solve(A, B)
# Use ddx and ddtheta to solve:
x_vec[i] = x_vec[i - 1] + dx_vec[i - 1] * dt
y_vec[i] = y_vec[i - 1] + dy_vec[i - 1] * dt
dx_vec[i] = dx_vec[i - 1] + ddx * dt
dy_vec[i] = dy_vec[i - 1] + ddy * dt
Problem 1 - Plots
#Generate the X and Y position plots
plt.plot(t_vec, x_vec)
plt.xlabel('Time (s)')
plt.ylabel('X Position')
plt.title("X Position over Time")
plt.show()
plt.plot(t_vec, y_vec)
plt.xlabel('Time (s)')
plt.ylabel('Y Position')
plt.title("Y Position over Time")
plt.show()
plt.plot(t_vec, lam_vec)
plt.xlabel('Time (s)')
plt.ylabel('Constraint Force (N)')
plt.title("Constraint Force over Time")
plt.show()
Problem 1 - Animation
#Set Up Figure for animation
fig, ax = plt.subplots()
# Create a plot on those axis
fig_size = 2
p, = ax.plot([], [], color = 'cornflowerblue') #Initializes empty plot
ax.set_xlim([-fig_size, fig_size])
ax.set_ylim([-1, 3])
ax.axis('equal')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Bead Simulation')
video_title = 'my_sim_p1'
#Define information for the video
FPS = 20
dpi = 300
#Create the bead
c = Circle((0, 0), radius = 0.1, color = 'cornflowerblue')
ax.add_patch(c) #Add the circle to the patch
#Define the sample rate and create a writer object
sample_rate = int(1/(FPS*dt)) #Samples to skip
writerObj = FFMpegWriter(fps = FPS)
#Create and plot the wire
x_wire_vec = np.arange(-fig_size, fig_size, 0.1)
y_wire_vec = [number ** 2 for number in x_wire_vec]
p.set_data(x_wire_vec, y_wire_vec)
# Create vectors for the simulation matrices
simulation_size = len(t_vec) #number of time points
# 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 bob circle
patch_center = x_vec[i], y_vec[i] #No brackets, just comma, creates a list
c.center = patch_center;
#Update drawing
fig.canvas.draw()
writerObj.grab_frame()
Problem 2 - Pendulum Spring System
Problem 2 - Imports
#HW1 Problem 2
import numpy as np
from numpy.linalg import solve
import matplotlib.pyplot as plt
from matplotlib.animation import FFMpegWriter
from matplotlib.patches import Circle, Rectangle
from matplotlib.lines import Line2D
Problem 2 - Simulation
#Define Constants
g = 9.8
m1 = 1
m2 = 2
L = 1
k = 10
H = 1.5
L_s = 1
#define time
dt = 0.001 # Time Step
sim_time = 10 # Length of Simulation
t_vec = np.arange(0, sim_time, dt)
#Initialize State Vectors
vec_size = len(t_vec)
x_vec = np.zeros(vec_size)
dx_vec = np.zeros(vec_size)
theta_vec = np.zeros(vec_size)
dtheta_vec = np.zeros(vec_size)
#Initial Conditions
x_vec[0] = 0
dx_vec[0] = 0
theta_vec[0] = 1
dtheta_vec[0] = 0
#Define information for the video
FPS = 20
dpi = 300
#Lets start simulating some stuff
A = np.array([[m2, 0], [0, m1*L**2]])
B = np.array([0, 0])
for i in range(1, vec_size):
#B must be updated every iteration
den = (L**2 - 2*L*x_vec[i-1]*np.sin(theta_vec[i-1]) + x_vec[i-1]**2 + H**2 - 2*H*L*np.cos(theta_vec[i-1]))**(0.5)
B[0] = k*L*np.sin(theta_vec[i-1]) - k*x_vec[i-1] + k*L_s*(x_vec[i-1] - L*np.sin(theta_vec[i-1]))/den
B[1] = (-m1*g*L*np.sin(theta_vec[i-1]) + k*L*x_vec[i-1]*np.cos(theta_vec[i-1]) - k*H*L*np.sin(theta_vec[i-1])) + k*L_s*(H*L*np.sin(theta_vec[i-1]) - L*x_vec[i-1]*np.cos(theta_vec[i-1]))/den
[ddx, ddtheta] = np.linalg.solve(A, B)
x_vec[i] = x_vec[i - 1] + dx_vec[i - 1] * dt
theta_vec[i] = theta_vec[i - 1] + dtheta_vec[i - 1] * dt
dx_vec[i] = dx_vec[i - 1] + ddx * dt
dtheta_vec[i] = dtheta_vec[i - 1] + ddtheta * dt
Problem 2 - Plots
#Generate the X and Y position plots
plt.plot(t_vec, x_vec)
plt.xlabel('Time (s)')
plt.ylabel('X Position')
plt.title("X Position over Time")
plt.show()
plt.plot(t_vec, theta_vec)
plt.xlabel('Time (s)')
plt.ylabel('Theta')
plt.title("Theta over Time")
plt.show()
Problem 2 - Animation
#Set Up Figure for animation
fig, ax = plt.subplots()
# Create a plot on those axis
p, = ax.plot([], [], color = 'cornflowerblue') #Initializes empty plot
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 3])
ax.axis('equal')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Pendulum Simulation')
video_title = 'my_sim_p2'
#Create the Pendulum mass
c = Circle((0, 0), radius = 0.1, color = 'cornflowerblue')
ax.add_patch(c) #Add the circle to the patch
#Create Block Mass
width = 0.2 # Width of Block
height = width / 2 # Height of Block
x_cart = (x_vec[0] - (width / 2), 0) # Bottom Left Corner of Cart
r = Rectangle(x_cart, width, height, color='cornflowerblue') # Rectangle Patch
ax.add_patch(r) # Add Patch to Plot
#Create Swivel
x_cart = (-0.1 / 2, H-0.1/2) # Bottom Left Corner of Cart
r2 = Rectangle(x_cart, 0.1, 0.1, color='black') # Rectangle Patch
ax.add_patch(r2) # Add Patch to Plot
#Create Lines
pend_arm = Line2D([0, 0], [0, 0])
ax.add_line(pend_arm)
spring = Line2D([0, 0], [0, 0])
ax.add_line(spring)
#Define the sample rate and create a writer object
sample_rate = int(1/(FPS*dt)) #Samples to skip
writerObj = FFMpegWriter(fps = FPS)
# Create vectors for the simulation matrices
simulation_size = len(t_vec) #number of time points
# 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 Pendulum Arm:
x_pole_arm = [0, L*np.sin(theta_vec[i])]
y_pole_arm = [H, H-L*np.cos(theta_vec[i])]
pend_arm.set_data([x_pole_arm, y_pole_arm])
# Update Spring
x_spring = [L*np.sin(theta_vec[i]), x_vec[i]]
y_spring = [H-L*np.cos(theta_vec[i]), height/2]
spring.set_data([x_spring, y_spring])
r.set(xy=(x_vec[i] - width / 2, 0))
#Update the bob circle
patch_center = L*np.sin(theta_vec[i]), 1.5-L*np.cos(theta_vec[i]) #No brackets, just comma, creates a list
c.center = patch_center;
#Update drawing
fig.canvas.draw()
writerObj.grab_frame()
Problem 3 - Paraboloid
Problem 3 - Imports
#HW1 Problem 3
import numpy as np
import math
from numpy.linalg import solve
import matplotlib.pyplot as plt
from matplotlib.animation import FFMpegWriter
from matplotlib.patches import Circle, PathPatch
from mpl_toolkits import mplot3d
import mpl_toolkits.mplot3d.art3d as art3d
Problem 3 - Simulation
#Define Constants
g = 9.8
m = 1
#define time
dt = 0.0001 # Time Step
sim_time = 10 # Length of Simulation
t_vec = np.arange(0, sim_time, dt)
#Initialize State Vectors
vec_size = len(t_vec)
x_vec = np.zeros(vec_size)
dx_vec = np.zeros(vec_size)
y_vec = np.zeros(vec_size)
dy_vec = np.zeros(vec_size)
z_vec = np.zeros(vec_size)
dz_vec = np.zeros(vec_size)
#Initial Conditions
x_vec[0] = 1
dx_vec[0] = 0
y_vec[0] = 0
dy_vec[0] = 1
z_vec[0] = (x_vec[0] ** 2) + (y_vec[0] ** 2)
dz_vec[0] = 2*(x_vec[0]*dx_vec[0] + y_vec[0]*dy_vec[0])
#Define information for the video
FPS = 20
dpi = 300
#Lets start simulating some stuff
#Fill in every element that wont change
A = np.array([[m, 0, 0, 0], [0, m, 0, 0] , [ 0, 0, m, (-1 - 0.000001)], [ 0, 0, -1, 0]])
B = np.array([0, 0, -m*g, 0])
for i in range(1, vec_size):
#Only Update Top right and bottom left
A[0, 3] = 2*x_vec[i-1]
A[1, 3] = 2*y_vec[i-1]
A[3, 0] = 2*x_vec[i-1]
A[3, 1] = 2*y_vec[i-1]
#Last element of b must be updated
B[3] = -2*((dx_vec[i-1] ** 2) + (dy_vec[i-1] ** 2))
[ddx, ddy, ddz, lam] = np.linalg.solve(A, B)
# Use ddx and ddtheta to solve:
x_vec[i] = x_vec[i - 1] + dx_vec[i - 1] * dt
y_vec[i] = y_vec[i - 1] + dy_vec[i - 1] * dt
z_vec[i] = z_vec[i - 1] + dz_vec[i - 1] * dt
dx_vec[i] = dx_vec[i - 1] + ddx * dt
dy_vec[i] = dy_vec[i - 1] + ddy * dt
dz_vec[i] = dz_vec[i - 1] + ddz * dt
Problem 3 - Plots
#Generate the X and Y position plots
plt.plot(t_vec, x_vec)
plt.xlabel('Time (s)')
plt.ylabel('X Position')
plt.title("X Position over Time")
plt.show()
plt.plot(t_vec, y_vec)
plt.xlabel('Time (s)')
plt.ylabel('Y Position')
plt.title("Y Position over Time")
plt.show()
#plt.plot(t_vec, z_vec)
#plt.xlabel('Time (s)')
#plt.ylabel('Z Position')
#plt.title("Z Position over Time")
#plt.show()
Problem 3 - Animation
def f(x, y):
return x ** 2 + y ** 2
x = np.linspace(-1, 1, 30)
y = np.linspace(-1, 1, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
#Set Up Figure for animation
fig, ax = plt.subplots()
plt.axis('off')
# Create a plot on those axis
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 30, cmap='binary')
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 1])
ax.set_zlim([0, 1])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Paraboloid Simulation')
video_title = 'my_sim_p3'
ax.view_init(60, 35)
#Define the sample rate and create a writer object
sample_rate = int(1/(FPS*dt)) #Samples to skip
writerObj = FFMpegWriter(fps = FPS)
# Create vectors for the simulation matrices
simulation_size = len(t_vec) #number of time points
# 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):
scat = ax.scatter3D(x_vec[i], y_vec[i], z_vec[i], color = 'cornflowerblue' )
ax.view_init(math.atan2(z_vec[i], np.sqrt(y_vec[i]**2 + x_vec[i]**2) )*180/3.1415, math.atan2(y_vec[i], x_vec[i])*180/3.1415)
#ax.view_init(35, 60)
#Update drawing
fig.canvas.draw()
writerObj.grab_frame()
scat.remove()