-
Notifications
You must be signed in to change notification settings - Fork 1
/
animation_nipendulum.py
62 lines (46 loc) · 1.58 KB
/
animation_nipendulum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
## Import the required modules
from pendulum.models import *
import matplotlib.pyplot as plt
import matplotlib.animation as animation
## Set-up your problem
g = 9.8 # Acceleration of gravity
l = 1 # Pendulum length
d = 1 # Damping
# Pivot's position
## The pivot is moving, so its position is a function of time
pos_x = lambda t : np.arctan(5*t)
pos_y = lambda t : 0*t
ts = np.linspace(-5, 10, 1000) # Simulation time
yinit = (0, 0) # Initial condition (th_0, w_0)
## Solve it
sol = pendulum(yinit, ts, pos_x, pos_y, g = g, l = l, d = d)
## Transform to cartesian coordinates
x_pivot = pos_x(ts) # Pivot's positions
y_pivot = pos_y(ts)
x = x_pivot + l*np.sin(sol[:, 0]) # Bob's positions
y = y_pivot - l*np.cos(sol[:, 0])
## Animate results
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal', xlim=(-3, 3), ylim=(-3, 3))
ax.grid()
line, = ax.plot([], [], 'o-', lw=1)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
def init():
line.set_data([], [])
time_text.set_text('')
return line, time_text
def animate(i):
thisx = [x[i], x_pivot[i]]
thisy = [y[i], y_pivot[i]]
line.set_data(thisx, thisy)
time_text.set_text(time_template % (ts[i]))
return line, time_text
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(ts)),
interval=2, blit=True, init_func=init)
## Uncomment for saving
# Set up formatting for the movie files
#Writer = animation.writers['ffmpeg']
#writer = Writer(fps=100, metadata=dict(artist='Me'), bitrate=1800)
#ani.save('im.mp4', writer = writer)
plt.show()