Lorenz attractor plotting example

This example is based on the following original matplotlib's example code:


In [1]:
require 'matplotlib/iruby'
Matplotlib::IRuby.activate
plt = Matplotlib::Pyplot

require 'pycall/import'
include PyCall::Import
pyimport :numpy, as: :np

require 'matplotlib/axes_3d' # enable 3d plot


Out[1]:
true

In [2]:
def lorenz(x, y, z, s: 10, r: 28, b: 2.667)
  x_dot = s * (y - x)
  y_dot = r * x - y - x * z
  z_dot = x * y - b * z
  [x_dot, y_dot, z_dot]
end


Out[2]:
:lorenz

In [3]:
dt = 0.01
stepCnt = 10_000


Out[3]:
10000

In [4]:
# Need one more for the initial values
xs = np.empty([stepCnt + 1])
ys = np.empty([stepCnt + 1])
zs = np.empty([stepCnt + 1])
nil

In [5]:
# Setting initial values
xs[0], ys[0], zs[0] = 0.0, 1.0, 1.05


Out[5]:
[0.0, 1.0, 1.05]

In [6]:
# Stepping through "time".
stepCnt.times do |i|
  # Derivatives of the X, Y, Z state
  x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i])
  xs[i + 1] = xs[i] + (x_dot * dt)
  ys[i + 1] = ys[i] + (y_dot * dt)
  zs[i + 1] = zs[i] + (z_dot * dt)
end


Out[6]:
10000

In [7]:
fig = plt.figure()
ax = fig.gca(projection: '3d')

ax.plot(xs, ys, zs, lw: 0.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")


Out[7]:
Out[7]:
#<Object:0x007fd68e27f800 @__pyptr__=#<PyCall::PyPtr:0x007fd68e27f7d8 type=Text addr=0x0000010a551588>>

In [ ]: