Path: blob/master/JSAnimation/make_lorenz_animation.py
934 views
"""1Lorenz animation23Adapted from http://jakevdp.github.io/blog/2013/02/16/animating-the-lorentz-system-in-3d/4"""56import numpy as np7from scipy import integrate89from matplotlib import pyplot as plt10from mpl_toolkits.mplot3d import Axes3D11from matplotlib.colors import cnames12from matplotlib import animation1314from JSAnimation import HTMLWriter1516N_trajectories = 20171819def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0):20"""Compute the time-derivative of a Lorentz system."""21return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]222324# Choose random starting points, uniformly distributed from -15 to 1525np.random.seed(1)26x0 = -15 + 30 * np.random.random((N_trajectories, 3))2728# Solve for the trajectories29t = np.linspace(0, 2, 500)30x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)31for x0i in x0])3233# Set up figure & 3D axis for animation34fig = plt.figure(figsize=(4, 3))35ax = fig.add_axes([0, 0, 1, 1], projection='3d')36ax.axis('off')3738# choose a different color for each trajectory39colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))4041# set up lines and points42lines = sum([ax.plot([], [], [], '-', c=c)43for c in colors], [])44pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)45for c in colors], [])4647# prepare the axes limits48ax.set_xlim((-25, 25))49ax.set_ylim((-35, 35))50ax.set_zlim((5, 55))5152# set point-of-view: specified by (altitude degrees, azimuth degrees)53ax.view_init(30, 0)5455# initialization function: plot the background of each frame56def init():57for line, pt in zip(lines, pts):58line.set_data([], [])59line.set_3d_properties([])6061pt.set_data([], [])62pt.set_3d_properties([])63return lines + pts6465# animation function. This will be called sequentially with the frame number66def animate(i):67# we'll step two time-steps per frame. This leads to nice results.68i = (2 * i) % x_t.shape[1]6970for line, pt, xi in zip(lines, pts, x_t):71x, y, z = xi[:i + 1].T72line.set_data(x, y)73line.set_3d_properties(z)7475pt.set_data(x[-1:], y[-1:])76pt.set_3d_properties(z[-1:])7778ax.view_init(30, 0.3 * i)79fig.canvas.draw()80return lines + pts8182# instantiate the animator.83anim = animation.FuncAnimation(fig, animate, init_func=init,84frames=200, interval=30, blit=True)8586# set embed_frames=False so that frames will be stored individually87anim.save('lorenz_animation.html', writer=HTMLWriter(embed_frames=False))8889909192