Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
restrepo
GitHub Repository: restrepo/ComputationalMethods
Path: blob/master/JSAnimation/template/make_lorenz_frames.py
934 views
1
import numpy as np
2
from scipy import integrate
3
4
from matplotlib import pyplot as plt
5
from mpl_toolkits.mplot3d import Axes3D
6
from matplotlib.colors import cnames
7
from matplotlib import animation
8
9
N_trajectories = 20
10
11
12
def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0):
13
"""Compute the time-derivative of a Lorentz system."""
14
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
15
16
17
# Choose random starting points, uniformly distributed from -15 to 15
18
np.random.seed(1)
19
x0 = -15 + 30 * np.random.random((N_trajectories, 3))
20
21
# Solve for the trajectories
22
t = np.linspace(0, 4, 1000)
23
x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
24
for x0i in x0])
25
26
# Set up figure & 3D axis for animation
27
fig = plt.figure()
28
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
29
ax.axis('off')
30
31
# choose a different color for each trajectory
32
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
33
34
# set up lines and points
35
lines = sum([ax.plot([], [], [], '-', c=c)
36
for c in colors], [])
37
pts = sum([ax.plot([], [], [], 'o', c=c)
38
for c in colors], [])
39
40
# prepare the axes limits
41
ax.set_xlim((-25, 25))
42
ax.set_ylim((-35, 35))
43
ax.set_zlim((5, 55))
44
45
# set point-of-view: specified by (altitude degrees, azimuth degrees)
46
ax.view_init(30, 0)
47
48
# initialization function: plot the background of each frame
49
def init():
50
for line, pt in zip(lines, pts):
51
line.set_data([], [])
52
line.set_3d_properties([])
53
54
pt.set_data([], [])
55
pt.set_3d_properties([])
56
return lines + pts
57
58
# animation function. This will be called sequentially with the frame number
59
def animate(i):
60
# we'll step two time-steps per frame. This leads to nice results.
61
i = (2 * i) % x_t.shape[1]
62
63
for line, pt, xi in zip(lines, pts, x_t):
64
x, y, z = xi[:i].T
65
line.set_data(x, y)
66
line.set_3d_properties(z)
67
68
pt.set_data(x[-1:], y[-1:])
69
pt.set_3d_properties(z[-1:])
70
71
ax.view_init(30, 0.3 * i)
72
fig.canvas.draw()
73
return lines + pts
74
75
# instantiate the animator.
76
#anim = animation.FuncAnimation(fig, animate, init_func=init,
77
# frames=500, interval=30, blit=True)
78
79
# Save as mp4. This requires mplayer or ffmpeg to be installed
80
#anim.save('lorentz_attractor.mp4', fps=15, extra_args=['-vcodec', 'libx264'])
81
82
#plt.show()
83
84
for i in range(100):
85
animate(2 * i + 1)
86
fig.savefig('frames/frame%.03i.png' % (i + 1), dpi=80)
87
88
89