Engee documentation
Notebook

Fibonacci spiral

In this example, we will show you how to use interactive scripts to conveniently compare the results of different models - graphical and textual.

We will build a graphical model generating points on the Fibonacci spiral and then compare the obtained graph with the result of calculating the golden spiral model.

The object under study

The Fibonacci spiral is an approximation of the golden spiral. It was described by Leonardo of Pisa (nicknamed Fibonacci) around 1202. It is defined by means of a piecewise linear curve consisting of quarters of circles. The radius of each quarter circle $n$ is given by a recurrence relation that forms the famous Fibonacci sequence:

$$F_0 = 0, ~ F_1 = 1, ~ F_n = F_{n-1} + F_{n-2}$$

where $n \geq 2, ~ n \in Z$.

(the first two terms 0, 1 are usually discarded, the spiral is built right from the third term: 1, 2, 3, 5, 7...)

The centre of each circle is chosen so that the spiral remains smooth. The points of the centre of each circle can be obtained from the model fibonacci_spiral_model.engee (signals cx and cy) along with their radii (signals r). Using the output signals x and y we will plot the Fibonacci spiral.

The general view of the model is presented below:

image.png

Golden spiral

The golden spiral is defined on the entire numerical axis by a single exponential function. This function is equally easy to define both by means of a mathematical expression and a graphical model. It is a logarithmic spiral, the radix of which, for each half turn $\pi/2$, increases by the value $\lambda = \frac{\sqrt{5}-1}{2} \approx 0.618$. Here $\lambda$ is the inverse of the golden ratio $\varphi \approx 1.618$.

We will have to complicate the usual equation of the logarithmic spiral $r = c \lambda^{(2/\pi)\theta}$. The point of convergence $(s_x, s_y)$ of the Fibonacci spiral is not at the origin of coordinates and depends on the size of the rectangle in which the Fibonacci spiral is inscribed. For coincidence of both spirals it is necessary also to enter in the equation of the golden spiral a non-zero angle of initial rotation $\alpha$.

For the derivation of the formula of the golden spiral, maximally coinciding with the Fibonacci spiral, it is better to refer to the publication [1]. Here we will give only the final formula of the golden spiral in polar coordinates:

$$r = \frac{a}{2 - \lambda}\sqrt{1 + \lambda^6} \lambda^{\frac{2}{\pi}(\theta + \alpha)}$$

where $(\theta, r)$ is a series of coordinates of points on the spiral in the polar coordinate system, $a$ is the width of the rectangle in which the Fibonacci spiral is inscribed.

Running the model

Let's run the model fibonacci_spiral_model.engee and analyse the results.

In [ ]:
modelName = "fibonacci_spiral_model";
model = modelName in [m.name for m in engee.get_all_models()] ? engee.open( modelName ) : engee.load( "$(@__DIR__)/$(modelName).engee");

This construction allowed us to check if the model was loaded and opened by the user (then we need the command open), or if it should be loaded using the command load.

Running the model is very simple:

In [ ]:
s = engee.run( modelName, verbose=false )
Out[0]:
Dict{String, DataFrame} with 3 entries:
  "x" => 1001×2 DataFrame…
  "r" => 11×2 DataFrame…
  "y" => 1001×2 DataFrame

The output object s contains tables with those signals that are marked as "logged" in the model (using the ).

Analysing the results

Let's choose an environment for drawing the graphs.

In [ ]:
using Plots

gr() # Статичные графики небольшого размера
#plotly() # Интерактивные графики по ширине экрана
Out[0]:
Plots.GRBackend()

Let's visualise a series of Fibonacci numbers: signal r. This vector contains rather few points, because the model that generates them has a low sampling rate.

In [ ]:
plot( s["r"].time, s["r"].value, label="Ряд Фибоначчи", st=:stem )

# Зададим собственные подписи для шкалы X
plot!( xticks=( range( minimum(s["r"].time), maximum(s["r"].time), step=1),
           Int.(range( minimum(s["r"].time), maximum(s["r"].time), step=1))) )
Out[0]:

Constructing a golden spiral

As we discussed, in order to construct a golden spiral that matches the Fibonacci spiral, we first need to get a few parameters from an already constructed spiral.

In [ ]:
theta = range( -0.8*pi, 12*pi, step=0.01); # Область определения золотой спирали

λ = (sqrt(5)-1)/2; # Число, обратное золотому сечению

# Размеры прямоугольника, в который вписана спираль Фибоначчи
a = maximum(s["x"].value) - minimum(s["x"].value)
b = maximum(s["y"].value) - minimum(s["y"].value)

# Координаты центра спирали Фибоначчи
# - в системе координат этого прямоугольника)
x = (1 - λ)/(2 - λ) * a
y = (1 - λ)/(2 - λ) * b
# - в системе координат графика
sx = minimum(s["x"].value) + x;
sy = maximum(s["y"].value) - y; # (учтем, что ось y направлена вверх)

# Угол поворота золотой спирали относительно спирали Фибоначчи
α = atan( 2*λ - 1 );

Now we can calculate the coordinates of the points lying on the golden spiral

In [ ]:
# Точки золотой спирали в полярной системе координат
R = @. (a/(2 - λ)) * sqrt(1 + λ^6) * λ^((2/pi)*(theta+α))
# Точки золотой спирали в декартовой системе координат
x,y =  R .* cos.( theta ) .+ sx, R .* sin.( theta ) .+ sy;

It remains to display both graphs for visual comparison.

In [ ]:
plot( s["x"].value, s["y"].value, lc=:skyblue, aspect_ratio=:equal, lw=4, label="Спираль Фибоначчи" )
plot!( x, y, lc=:black, ls=:dash, label="Золотая спираль", legend=:topleft )
Out[0]:

It is obvious that the models match quite well.

Conclusions

We used Engee basic blocks to build a mathematical model that approximates the golden spiral. Then, using software control commands, we visualised several signals and compared the result with the golden spiral equation.

Reference:

[1] Duan J. S. Shrinkage points of golden rectangle, Fibonacci spirals, and golden spirals //Discrete Dynamics in Nature and Society. - 2019. - Т. 2019. - С. 1-6.