Debian Codegraph @

examples/02-plot/lorenz_attractor.py

raw
1 """
2 .. _lorenz_attractor_example:
3
4 Plot a Lorenz Attractor
5 ~~~~~~~~~~~~~~~~~~~~~~~
6
7 Integrate the Lorenz system and render the trajectory as a colored tube
8 built from :func:`pyvista.lines_from_points`.
9 """
10
11 import numpy as np
12 import pyvista as pv
13
14 # %%
15 # Integrate the Lorenz system
16 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 # A forward-Euler scheme is enough to trace the chaotic trajectory.
18
19 sigma = 10.0
20 rho = 28.0
21 beta = 8.0 / 3.0
22 dt = 0.01
23 n_steps = 8000
24
25 points = np.empty((n_steps + 1, 3))
26 points[0] = (0.0, 1.0, 1.05)
27
28 for i in range(n_steps):
29 x, y, z = points[i]
30 points[i + 1] = (
31 x + sigma * (y - x) * dt,
32 y + (x * (rho - z) - y) * dt,
33 z + (x * y - beta * z) * dt,
34 )
35
36 trajectory = pv.lines_from_points(points)
37 trajectory['z'] = points[:, 2]
38
39
40 # %%
41 # Render the attractor
42 # ~~~~~~~~~~~~~~~~~~~~
43 # Tube the polyline so the trajectory has visible thickness in 3D.
44
45 pl = pv.Plotter()
46 pl.add_mesh(trajectory.tube(radius=0.12), scalars='z', cmap='plasma')
47 pl.show()
48
49
50 # %%
51 # Inspect the path length
52 # ~~~~~~~~~~~~~~~~~~~~~~~
53 # The integrated trajectory accumulates several hundred units of arc length.
54
55 trajectory.length
56 # %%
57 # .. tags:: plot