"""Module that calculates the mandelbrot set for a given range. It uses a c extensions to speed up the computation."""
import ctypes
import os.path
import sys
LIB_EXT = 'dylib' if sys.platform == 'darwin' else 'so'
libmandel = ctypes.CDLL(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'libmandel.{ext}'.format(ext=LIB_EXT)))
libmandel.mandel.argtypes = [ctypes.c_longdouble, ctypes.c_longdouble, ctypes.c_int]
libmandel.mandel.restype = ctypes.c_int
[docs]def mandel(x, y, iters):
"""Compute the mandelbrot set at a given point.
Calculates how many iterations are needed at a given point to determine if the mandelbrot sequence is divergent.
:param x: x component of the point where to calculate the mandelbrot sequence
:type x: double
:param y: y component of the point where to calculate the mandelbrot sequence
:type y: double
:param iters: Maximum number of iterations that are calculated to check if the mandelbrot sequence does converge.
:type iters: int
:returns: Numbers of iterations scaled to the interval [0, 255].
:rtype: int
"""
return libmandel.mandel(x, y, iters)
[docs]def create_fractal(min_x, max_x, min_y, max_y, image, iters):
"""Compute the mandelbrot set in a given range.
:param min_x: Minimum x value of the range where to calculate the mandelbrot set
:type min_x: double
:param max_x: Maximum x value of the range where to calculate the mandelbrot set
:type max_x: double
:param min_y: Minimum y value of the range where to calculate the mandelbrot set
:type min_y: double
:param max_y: Maximum y value of the range where to calculate the mandelbrot set
:type max_y: double
:param image: Array for the storage of mandelbrot set calculation results
:type image: 2 dimensional numpy array
:param iters: Maximum number of iterations that are calculated to check if the mandelbrot sequence does converge
:type iters: int
:returns: Array that was passed as ``image`` argument
:rtype: 2 dimensional numpy array
"""
height = image.shape[0]
width = image.shape[1]
pixel_size_x = (max_x - min_x) / width
pixel_size_y = (max_y - min_y) / height
for x in range(width):
real_x = min_x + x * pixel_size_x
for y in range(height):
real_y = min_y + y * pixel_size_y
image[y, x] = mandel(real_x, real_y, iters)
return image