Engee documentation
Notebook

Creating fractal animation based on the Julia set

Introduction

In 1918, French scientist Gaston Julia investigated the behavior of complex functions during iteration, but it was only with the advent of computers that the world saw the beauty hidden in his equations.

The Julia set is the visual embodiment of the boundary between order and chaos. A simple equation creates an infinite variety of self-similar fractals, where each point rushes to infinity or remains in a limited area.

In this example, we will look at how to use complex numbers, iterations, and color schemes to create an animation of a Julia set shape that changes its state depending on the changing angle of the constant.

We will attach the necessary libraries.

In [ ]:
# import Pkg
# Pkg.add(["LinearAlgebra", "Printf", "ProgressMeter", "FileIO", "Images", "ColorSchemes", "VideoIO"])
using LinearAlgebra, Printf, ProgressMeter, FileIO, Images, ColorSchemes, VideoIO

Shape and animation parameters

Define the animation parameters. Required parameters:

  • Animation duration;
  • frame width;
  • Frame height;
  • number of frames per second;
  • the initial angle of the constant;
  • the final angle of the constant;
  • radius of the shape;
  • number of iterations;
  • dimensions of the complex plane (transformed proportionally to the width and height of the frame).
In [ ]:
сек = 60  # animation duration
ш = 1920  # frame width
в = 1080  # frame height
квс = 60  # frames per second
α = 2π*0.14  # the initial angle of the constant
β = 2π*0.86  # the final angle of the constant
r = 0.78  # radius
итер = 20  # number of iterations
л = 1.5  # linear width of the complex plane

The complex plane

Based on the initial ones, we will calculate the number of frames in the animation and create arrays of numbers for the complex plane. Where – array of the real part, – an array of imaginary parts.

In [ ]:
кадры = сек * квс  # total frames
# Creating a complex plane
X = [x for y in range(-l, l, length=h), x in range(-l, l, length=w)];
Y = [y for y in range(-l, l, length=h), x in range(-l, l, length=w)];

A function with an expression and iterations

Let's define a function that calculates each complex number and performs iterations of calculating the function and substituting the resulting values into the function argument.

The function is defined as follows:

,

where:

,

,

- the changing angle of the constant, affecting the animation of the figure,

- imaginary unit.

In [ ]:
Julia's function(X, Y, a, r, iter)
    Z = X .+ im .* Y
    C = r .* cos(a) .+ im .* r .* sin(a)
    
    for k in 1:iteration
        Z = Z .^ 2 .+ C
    end
    return exp.(-abs.(Z)), C
end

Creating subtitles

Let's define a function that creates subtitles in the srt format to display the current Z value corresponding to the current state of the shape.

In [ ]:
function_frame time(k, kvs)
    T = zeros(UInt32, 4)
    квч = 3600 * квс  # frames per hour
    квм = 60 * квс    # frames per minute
    бч = mod(к, квч)  # shots without a watch
    бм = mod(бч, квм)  # frames without minutes and hours
    T[1] = (к - бч) ÷ квч  # watch
    T[2] = (бч - бм) ÷ квм  # minutes
    T[4] = mod(бм, квс)  # frames without seconds, minutes, or hours
    T[3] = (бм - T[4]) ÷ квс  # seconds
    ms = round(Int, 999 * T[4] / (fac - 1))
    субт = string(lpad(T[1], 2, '0'), ':', lpad(T[2], 2, '0'), ':', lpad(T[3], 2, '0'), ',', lpad(мс, 3, '0'))
    return subt
end

Creating animations

Let's create a progress bar and start the animation creation process.

In [ ]:
frame = 0
t = 0.0
Time = 0.0
video = []
п = Progress(кадры, 1, "Creating animations:")
субтитры = open("Julia's set.srt", "w")
ProgressMeter.ijulia_behavior(:clear)
for a in range(α + (β - α)/frames, stop = β, step = (β - α)/frames)
    start = time()
    time += t
    frame += 1 
    speed = frame/max(time, 0.001)
    remaining = (frames - frame) / speed
    ProgressMeter.next!(п; showvalues = [(:Время, @sprintf "%d seconds" round(Int, время)), (:Создано, @sprintf "%d frames" кадр), (:Скорость, @sprintf "%.4f frames per second" скорость), (:Осталось, @sprintf "%d seconds" round(Int, осталось))])
    J, C = Julia(X, Y, a, r, iter)
    J[isnan.(J)] .= 0.0
    push!(video, convert.(RGB{N0f8}, get.(Ref(ColorSchemes.magma), clamp.(J, 0.0, 1.0))))
    write(субтитры, string(string(кадр), "\n", кадр_время(кадр-1, квс), " --> ", кадр_время(кадр, квс), "\n", "f(z) = z² ", real(C) >= 0 ? "+ " : "- ", @sprintf("%.5f", abs(real(C))), " ", imag(C) >= 0 ? "+ " : "- ", @sprintf("%.5fi", abs(imag(C))), "\n\n"))
    t = time() - start
end

if !isempty(video)
    @info "Saving the video..."
    параметры = (crf=23, preset="medium")
    VideoIO.save("Lots of Julia.mp4", видео, framerate=квс, encoder_options=параметры)
end

close(subtitles)

println("\The intensive care unit was created successfully!")
println("  - Total frames: $frames")
println("  - Creation time: $(round(Int, time)) seconds")
println("  - Average creation rate: $(round(frames/time, digits=4)) frames per second")

After completing the animation creation process, a video file with a figure will appear in the current folder.:

Z^2.gif

If in the function that evaluates the iteration instead of the expression replace with , and replace the color scheme with turbo, we will get an equally interesting figure.

Z^3.gif

If we define the expression as by replacing the color scheme with rainbow, we get an even more unusual shape.

Z^Z.gif

Conclusion

The created animation of the Julia set demonstrates not only the aesthetic, but also the applied value of fractal geometry. Algorithms based on the principles of iterative transformations of the complex plane are used in various scientific and engineering fields.

Key areas of application

  • Telecommunications.
    Fractal antennas with a self-similar structure provide multiband with minimal dimensions, which is critical for mobile devices and satellite communications.
  • Computer modeling.
    Fractal generation algorithms are used to synthesize natural landscapes in computer graphics, as well as to model porous materials and biological structures.
  • Medical diagnostics.
    Fractal analysis is used in medical image processing to quantify the complexity of blood vessels, neural networks, and lung tissue.
  • Cryptography and data protection.
    Deterministic chaos of fractal systems is used in pseudorandom number generators and steganographic methods.

Thus, from an abstract mathematical object to a practical tool, fractals represent an important bridge between theoretical mathematics and applied technologies. The presented animation technique allows not only to visualize these concepts, but also to experiment with parameters to explore the boundaries between order and chaos in dynamic systems.