The functions used in the previous post generate an array of integers, the number of iterations for the function return value to exceed 2. This post looks in more detail at how this data can be plotted in Excel using the Matplotlib imshow function and pyxll.
First the Mandelbrot data is generated using the fastest of the functions described in the previous post, then new Matplotlib fig and ax objects are created:
The imshow function requires cmap and norm arguments:
cmap str or Colormap, default: rcParams["image.cmap"] (default: 'viridis'): The Colormap instance or registered colormap name used to map scalar data to colors.
normNormalize, optional: The Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used.
Norm is set using colors.PowerNorm:
Linearly map a given value to the 0-1 range and then apply a power-law normalization over that range.
ax.imshow is used to generate the image, then pyxll.plot to copy the image to Excel:
As promised in the previous post, this post will look at alternative procedures for calculating and plotting the Mandelbrot set with Python based code.
Input data for the two images, and times for the 7 routines to generate the data are shown in the screenshot below:
The second image is zoomed in by a factor of 100,000, which requires many more iterations to define the image, resulting in execution times 20-50 times longer.
The first function uses plain Python, which works very slowly, but illustrates the simplicity of the computation used to generate the complex images, with repeated looping through the procedure:
# 0 All python
def mandelbrot(z,maxiter):
c = z
for n in range(maxiter):
if abs(z) > 2:
return n
z = z*z + c
return maxiter
@xl_func
@xl_arg('width', 'int')
@xl_arg('height', 'int')
@xl_arg('maxiter', 'int')
def mandelbrot_set0(xmin,xmax,ymin,ymax,width,height,maxiter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
res = (r1,r2,[mandelbrot(complex(r, i),maxiter) for r in r1 for i in r2])
return res
The next two functions replace lists with Numpy arrays, but the result is even slower:
# 1 Relace lists with Numpy arrays
@xl_func
@xl_arg('width', 'int')
@xl_arg('height', 'int')
@xl_arg('maxiter', 'int')
def mandelbrot_set1(xmin,xmax,ymin,ymax,width,height,maxiter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
n3 = np.empty((width,height))
for i in range(width):
for j in range(height):
n3[i,j] = mandelbrot(r1[i] + 1j*r2[j],maxiter)
res = (r1,r2,n3)
return res
See the download file for the second function using Numpy arrays (which is even slower).
Using the Numba jit compiler greatly increases the speed of the code, and is very simple to use, just requiring the addition of the @njit decorator to the start of the code:
# 3 Compile code with Numba
@njit
def mandelbrot3(c,maxiter):
z = c
for n in range(maxiter):
if abs(z) > 2:
return n
z = z*z + c
return 0
@xl_func
@xl_arg('width', 'int')
@xl_arg('height', 'int')
@xl_arg('maxiter', 'int')
@njit
def mandelbrot_set3(xmin,xmax,ymin,ymax,width,height,maxiter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
n3 = np.empty((width,height))
for i in range(width):
for j in range(height):
n3[i,j] = mandelbrot3(r1[i] + 1j*r2[j],maxiter)
res = (r1,r2,n3)
return res
Removing the square root operation from the code resulted in a further doubling of the speed, but replacing the complex number operations with two floats made almost no difference (see download file for details). Using the Numba fastmath function (function 7) gave a small increase in performance, but the @guvectorize() decorator resulted in a ten times increase in speed; a total speed improvement of about 1000 times for the second image:
# 6 Use guvectorize
@njit(int32(complex128, int64))
def mandelbrot6(c,maxiter):
nreal = 0
real = 0
imag = 0
for n in range(maxiter):
nreal = real*real - imag*imag + c.real
imag = 2* real*imag + c.imag
real = nreal;
if real * real + imag * imag > 4.0:
return n
return 0
@guvectorize([(complex128[:], int64[:], int64[:])], '(n),()->(n)',target='parallel')
def mandelbrot_numpy(c, maxit, output):
maxiter = maxit[0]
for i in range(c.shape[0]):
output[i] = mandelbrot6(c[i],maxiter)
@xl_func
@xl_arg('width', 'int')
@xl_arg('height', 'int')
@xl_arg('maxiter', 'int')
def mandelbrot_set6(xmin,xmax,ymin,ymax,width,height,maxiter):
r1 = np.linspace(xmin, xmax, width, dtype=np.float64)
r2 = np.linspace(ymin, ymax, height, dtype=np.float64)
c = r1 + r2[:,None]*1j
n3 = mandelbrot_numpy(c,maxiter)
res = (r1,r2,n3.T)
return res
Having generated the Mandelbrot data, a graph can be generated in Excel using Matplotlib and the pyxll plot function:
The appearance of the image can be varied with the two chart properties “cmap” and colors.PowerNorm. There are 166 named color maps, which have been listed on the spreadsheet using the lengthy code below:
The appearance of any colormap can be seen in the chart simply by entering the index number in cell B18. Similarly the PowerNorm value (between 0 and 1) may be entered in cell B19.
The chart is created by entering the Mandelbrot_Image function in any cell, as shown in the first two images of this post. More details of the plotting function, and examples of the colormaps, will be given in the next post.
A convenient way to create an animation in Excel is to create on-sheet formulas or user defined functions to generate the required data, then use VBA to iterate through the range of input values so that the chart or image will update for each iteration. A problem with this approach is that often the image will not redraw, while the code is running.
Searching for a solution to this problem, there were surprisingly few discussions on this problem, and most of those I did find I couldn’t get to work, but eventually I found a solution using ActiveWindow.SmallScroll, which has the twin benefits of being very simple, and obvious how it works. Example VBA code is shown below.
Edit 2 Dec. 2021: Modifications to the code for generating the images resulted in very short cycle times, so I added some code to “sleep” between cycles, so the cycle time was at least 1 second. Sleep is a Windows function, so has to be “declared” at the top of the code module. I have also added code to time each iteration, so the sleep period is reduced as the time for generating the image increases. An added benefit of this code is that it has removed the white screen flashing between each iteration, so the resulting video is much smoother.
#If VBA7 Then ' Excel 2010 or later
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)
#Else ' Excel 2007 or earlier
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
#End If
Sub Zoomin()
Dim Startfact As Double, inc As Double, steps As Long, Fact As Double
Worksheets("Sheet4").Activate
With Application.ActiveSheet
Startfact = Range("Start").Value
inc = Range("Factor").Value
steps = Range("steps").Value
Fact = Startfact
For i = 1 To steps
STime = Timer()
Range("Scale").Value = Fact
Range("Iteration") = i
ActiveWindow.SmallScroll down:=1
ActiveWindow.SmallScroll up:=1
Fact = Fact * inc
TimeDiff = (Timer() - STime) * 1000
If TimeDiff < 950 Then
Sleep (1000 - TimeDiff)
Else
Sleep (50)
End If
Next i
End With
End Sub
An example animation generated with this routine (plus a Python user defined function to generate the images) is shown below. More details of the code for generating the images will be provided in a later post:
Zoom in x2 24 times
With the faster image generation I have added a second video zooming in 48 times, with a final magnification of 2.8E+14 times, which is about as far as you can get with the resolution allowed with 64 bit float values:
Following some recent comments Graeme Dennes has released the latest version the Tanh-Sinh Quadrature spreadsheet with some corrections to the test function documentation.
For more information on the last major release see Numerical Integration With Tanh-Sinh Quadrature v 5.0. For more background information and numerous examples search this site for Tanh-Sinh, or select Numerical Integration from the categories drop down.
As always, if you have any questions or comments, please leave a comment below.
Every so often I check YouTube to see what new old music has been posted, and today I found:
Haitian Fight Song, here played by Danny Thompson in Norway in 1968
and Bert Jansch and Danny Thompson playing Thames Lighterman (great pictures as well as great music):
Bert Jansch composition. Recorded at the BBC for John Peel’s Night Ride, broadcast Dec 18, 1968. Apologies for poor sound quality: taken from 50 year old 1/4″ 4-track mono tape running at 3 3/4 ips. The title refers to Pentangle roadie Bobby Cadman, whose previous occupation had been Thames Lighterman. Bert’s song “One For Jo” is also about him, addressed to Bobby’s wife.