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