-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanimation_double_pendulum.py
70 lines (53 loc) · 1.85 KB
/
animation_double_pendulum.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
63
64
65
66
67
68
69
70
## Import the required modules
from pendulum.models import *
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
## Set-up your problem
m = (2, 1) # Masses
l = (1, 1) # Lengths
# Pivot's position
## The pivot is moving, so its position is a function of time
pos_x = lambda t : np.arctan(3*t) #-2 + np.arctan(3*(t - 1)) - np.arctan(3*(t - 7))
pos_y = lambda t : 0.0*t
ts = np.linspace(-3, 8, 1000) # Simulation time
yinit = (0, 0, 0, 0) # Initial condition (th_1, w_1, th_2, w_2)
## Solve it
sol = double_pendulum(yinit, ts, pos_x, pos_y, m=m, l=l)
## Transform to cartesian coordinates
x_0 = pos_x(ts) # Pivot's positions
y_0 = pos_y(ts)
x_1 = x_0 + l[0]*np.sin(sol[:, 0]) # Bob's positions
y_1 = y_0 - l[0]*np.cos(sol[:, 0])
x_2 = x_1 + l[1]*np.sin(sol[:, 2])
y_2 = y_1 - l[1]*np.cos(sol[:, 2])
## Animate results
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal', xlim=(-3, 3), ylim=(-3, 3))
ax.grid()
line_1, = ax.plot([], [], 'o-', lw=1)
line_2, = ax.plot([], [], 'o-', lw=1)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
def init():
line_1.set_data([], [])
line_2.set_data([], [])
time_text.set_text('')
return line_1, line_2, time_text
def animate(i):
xs_1 = [x_1[i], x_0[i]]
ys_1 = [y_1[i], y_0[i]]
xs_2 = [x_2[i], x_1[i]]
ys_2 = [y_2[i], y_1[i]]
line_1.set_data(xs_1, ys_1)
line_2.set_data(xs_2, ys_2)
time_text.set_text(time_template % (ts[i]))
return line_1, line_2, time_text
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(ts)),
interval=2, blit=True, init_func=init)
## Uncomment for saving
# Writer = animation.writers['ffmpeg']
# writer = Writer(fps=100, metadata=dict(artist='Me'), bitrate=1800)
# ani.save('im.mp4', writer = writer)
plt.show()