|
| 1 | +""" |
| 2 | +Lorenz System Animation |
| 3 | +======================= |
| 4 | +
|
| 5 | +Example of the Lorenz attractor. |
| 6 | +""" |
| 7 | + |
| 8 | +# test_example = false |
| 9 | +# sphinx_gallery_pygfx_docs = 'animate 10s' |
| 10 | + |
| 11 | +import fastplotlib as fpl |
| 12 | +import numpy as np |
| 13 | + |
| 14 | + |
| 15 | +# generate data |
| 16 | +def lorenz(xyz, *, s=10, r=28, b=2.667): |
| 17 | + """ |
| 18 | + Parameters |
| 19 | + ---------- |
| 20 | + xyz : array-like, shape (3,) |
| 21 | + Point of interest in three-dimensional space. |
| 22 | + s, r, b : float |
| 23 | + Parameters defining the Lorenz attractor. |
| 24 | +
|
| 25 | + Returns |
| 26 | + ------- |
| 27 | + xyz_dot : array, shape (3,) |
| 28 | + Values of the Lorenz attractor's partial derivatives at *xyz*. |
| 29 | + """ |
| 30 | + x, y, z = xyz |
| 31 | + x_dot = s * (y - x) |
| 32 | + y_dot = r * x - y - x * z |
| 33 | + z_dot = x * y - b * z |
| 34 | + return np.array([x_dot, y_dot, z_dot]) |
| 35 | + |
| 36 | + |
| 37 | +dt = 0.01 |
| 38 | +num_steps = 3_000 |
| 39 | + |
| 40 | +lorenz_data = np.empty((5, num_steps + 1, 3)) |
| 41 | + |
| 42 | +for i in range(5): |
| 43 | + xyzs = np.empty((num_steps + 1, 3)) # Need one more for the initial values |
| 44 | + xyzs[0] = (0., (i * 0.3) + 1, 1.05) # Set initial values |
| 45 | + # Step through "time", calculating the partial derivatives at the current point |
| 46 | + # and using them to estimate the next point |
| 47 | + for j in range(num_steps): |
| 48 | + xyzs[j + 1] = xyzs[j] + lorenz(xyzs[j]) * dt |
| 49 | + |
| 50 | + lorenz_data[i] = xyzs |
| 51 | + |
| 52 | +figure = fpl.Figure( |
| 53 | + cameras="3d", |
| 54 | + controller_types="fly" |
| 55 | +) |
| 56 | + |
| 57 | +lorenz_line = figure[0, 0].add_line_collection(data=lorenz_data, thickness=.1, cmap="tab10") |
| 58 | + |
| 59 | +scatter_markers = list() |
| 60 | + |
| 61 | +for graphic in lorenz_line: |
| 62 | + marker = figure[0, 0].add_scatter(graphic.data.value[0], sizes=8, colors=graphic.colors[0]) |
| 63 | + scatter_markers.append(marker) |
| 64 | + |
| 65 | +# initialize time |
| 66 | +time = 0 |
| 67 | + |
| 68 | + |
| 69 | +def animate(supblot): |
| 70 | + global time |
| 71 | + |
| 72 | + time += 2 |
| 73 | + |
| 74 | + if time >= xyzs.shape[0]: |
| 75 | + time = 0 |
| 76 | + |
| 77 | + for scatter, g in zip(scatter_markers, lorenz_line): |
| 78 | + scatter.data = g.data.value[time] |
| 79 | + |
| 80 | + |
| 81 | +figure[0, 0].add_animations(animate) |
| 82 | + |
| 83 | +figure.show() |
| 84 | + |
| 85 | +# set initial camera position to make animation in gallery render better |
| 86 | +figure[0, 0].camera.world.z = 75 |
| 87 | + |
| 88 | +# NOTE: `if __name__ == "__main__"` is NOT how to use fastplotlib interactively |
| 89 | +# please see our docs for using fastplotlib interactively in ipython and jupyter |
| 90 | +if __name__ == "__main__": |
| 91 | + print(__doc__) |
| 92 | + fpl.run() |
0 commit comments