Pendulum
In the following project, program is written to solve the ordinary differential equation of simple pendulum and plotting the results are various time steps to generate the animation at the end.
The motion of simple pendulum is represented using following ODE:
`(d^2theta)/dt^2 + b/m (d theta)/dt + g/l(sin theta) = 0`
Here,
g = gravity in m/s
l = length in m
m = mass in kg
b = damping coefficient.
In this program scipy librabry in python is used to solve the ODE using ode int function.
A seprate function is defined to solve the differential equations which can be called to solve and simulate the simulate motion for specified angular displacement and angular velocity using theta values.
Below is the program
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
import os
import imageio
# function that returns dz/dt
def model(theta,t,b,g,l,m):
theta1 = theta[0]
theta2 = theta[1]
dtheta1_dt = theta2
dtheta2_dt = -(b/m)*theta2-(g/l)*math.sin(theta1)
dtheta_dt = [dtheta1_dt,dtheta2_dt]
return dtheta_dt
# Variables
b=0.05
g=9.81
l=1 #meter
m= 1 #kg
# intial conditions
theta_0 = [0,3] # Intital angular velocity as 3m/s
# generating time points
t = np.linspace(0,20,200)
# Solving ode
theta = odeint(model, theta_0,t,args =(b,g,l,m))
# plots
plt.figure(1)
plt.title(\'Displacement and velocity of Pendulum\')
plt.plot(t,theta[:,0],\'g-\', label = \'Angular Displacement\')
plt.plot(t,theta[:,1],\'b--\', label = \'Angular Velocity\')
plt.savefig(\'Displacement and velocity of Pendulum.png\')
# Plotting Pendulum
x0 = 0
y0 = 3
x = theta[:,0]
print(len(x))
x1 = []
y1 = []
ct = 0
for i in x:
x1 = l*math.sin(i)
y1 = -l*math.cos(i)
ct = ct+1
filename = \'p_%05d.png\' % ct
path = \'E:/py_prog/Pendulum\'
plt.figure()
plt.plot([x0,x1],[y0,y1],linewidth=5,color=\'r\')
plt.plot(x1,y1,marker = \'o\',color=\'b\',markersize= 20)
plt.plot([-3,3,3,-3,-3],[4,4,3,3,4],\'g--\',linewidth = 5)
plt.xlim(-3,3)
plt.ylim(-3,4)
file_path = os.path.join(path, filename)
plt.savefig(file_path)
# Creating animation.
png_dir = \'E:/py_prog/Pendulum\'
images = []
for file_name in os.listdir(png_dir):
if file_name.endswith(\'.png\'):
file_path = os.path.join(png_dir, file_name)
images.append(imageio.imread(file_path))
imageio.mimsave(\'E:/py_prog/pendulum/pendulum_2.avi\', images)
Here imageio librabry in python ise used to create the animationa and save the generated file in avi format.