Week 3 - Solving second order ODEs
Aim: To simulate the transient behaviour of a simple pendulum
Objective:
- To Write a program in python to solve the ODE that will simulate the pendulum motion.
- Upload an animation on You tube and provide the You tube link for an animation in your report.
Explanation:
- The initial values of g , l , m ,b and angular displacement and angular velocity are given.
- Then the timespan values are added from 0-20 seconds in 240 steps for smooth motion of the pendulum.
- The odeint code is then used to solve the ODE.
- For loop is used to predict the motion of the pendulum for different values of time.
- All the positions of the pendulum are then saved in different plots.
- The video is created by imagemagick and stored and uploaded to the youtube.
import numpy as np
from scipy.integrate import odeint
import math
import matplotlib.pyplot as plt
from PIL import Image
import os
# ODE function
def system(theta,t,b,g,l,m):
theta1 = theta[0]
theta2 = theta[1]
dtheta1_dt = theta2
dtheta2_dt = -(b/m)*theta2-g*math.sin(theta1)
dtheta_dt = [dtheta1_dt,dtheta2_dt]
return dtheta_dt
# Defining constants
b = 0.05
g = 9.81
l = 5
m = 1
# initial conditions
theta_0 = [0,3]
#time plot
t = np.linspace(0,20,240)
# solving ode
theta = odeint(system,theta_0,t,args = (b,g,l,m))
# for animation and plots
f = 1
for i in range(0,240):
filename = str(f) + '.png'
f = f + 1
plt.figure()
plt.plot([10,l*math.sin(theta[i,0])+10],[10,10-l*math.cos(theta[i,0])],marker="o")
plt.xlim([0,20])
plt.ylim([0,20])
plt.savefig(filename)
plt.plot(t,theta[:,0],'b-')
plt.plot(t,theta[:,1],'r--')
plt.show()
def convert_to_gif(folder_path, gif_filename):
image_files = [f for f in os.listdir(folder_path) if f.endswith('.png')]
image_files.sort() # Ensure the images are sorted alphabetically
images = []
for image_file in image_files:
image_path = os.path.join(folder_path, image_file)
img = Image.open(image_path)
images.append(img)
gif_path = os.path.join(folder_path, gif_filename)
images[0].save(
gif_path,
save_all=True,
append_images=images[1:],
loop=0, # Loop indefinitely (0) or a specific number of times
# Duration between frames (in milliseconds)
)
print(f"Saved the GIF as {gif_path}")
if __name__ == "__main__":
folder_path = "D:\Python" # Replace this with the path to your folder containing PNG images
gif_filename = "result.gif" # Replace this with the desired GIF filename
convert_to_gif(folder_path, gif_filename)
Conclusion
The created file was an gif file, so cannot be uploaded to the youtube.
Therefore the gif file was attached here.