In [41]:
version = 4.0
# Math libraries
import numpy as np
from math import sqrt
# Matplotlib plotting libraries
import matplotlib.pyplot as plt
%matplotlib inline
# Bokeh plotting libraries
import bokeh.plotting as blt
blt.output_notebook()
Calculate JuliaSets
In [2]:
class JuliaSet(object):
def __init__(self, c, p, q, n=100):
self.c = c
self.n = n
self.p = p
self.q = q
self._d = .001
self.set = np.array([])
self._complexplane = np.array([])
def juliamap(self, z):
return z**2 + self.c
def iterate(self, z):
m = 0
while True:
z = self.juliamap(z)
m +=1
if abs(z)>2:
return m
elif m>=self.n:
return 0
#def my_range(self, start, end, step):
# while start <= end:
# yield start
# start += step
def gen_complexplane(self):
arr = np.arange(self.p, self.q, self._d)
#arr = np.linspace(-2,2,1000)
x, y = np.meshgrid(arr, arr)
self._complexplane = x+y*1j
def set_spacing(self, d):
self._d = d
self.gen_complexplane()
#print('spacing is now ' + repr(self._d) )
def generate(self):
i = np.vectorize(self.iterate)
self.set = i(self._complexplane)
return self.set
Create class to create plots of JuliaSet
In [3]:
class JuliaSetPlot(JuliaSet):
"""Extend JuliaSet to add plotting functionality"""
def __init__(self, *args, **kwargs):
# Invoke constructor for JuliaSet first, unaltered
JuliaSet.__init__(self, *args, **kwargs)
# Add another attribute: a rendered image array
self.img = np.array([])
def get_dim(self):
"""Return linear number of points in axis"""
return int((self.q-self.p) / self._d)
def render(self):
"""Render image as square array of ints"""
if not self.set.any(): self.generate()
# Convert inefficient list to efficient numpy array
self.img = np.array(self.set)
# Reshape array into a 2d complex plane
dim = int(sqrt(self.img.size))
print(self.img.size)
#self.img = np.reshape(self.img, (dim,dim)).T
def show(self):
"""Use matplotlib to plot image as an efficient mesh"""
if not self.img.size: self.render()
plt.figure(1, figsize=(12,9))
xy = np.linspace(self.p,self.q,int(sqrt(self.img.size)))
plt.pcolormesh(xy, xy, self.img, cmap=plt.cm.hot)
plt.colorbar()
plt.show()
def interact(self):
"""Use bokeh to plot an interactive image"""
from matplotlib.colors import rgb2hex
if not self.img.size: self.render()
# Mimic matplotlib "hot" color palette
colormap = plt.cm.get_cmap("hot")
bokehpalette = [rgb2hex(m) for m in colormap(np.arange(colormap.N))]
# Create bokeh figure
f = blt.figure(x_range=(self.p,self.q), y_range=(self.p,self.q), plot_width=600, plot_height=600)
f.image(image=[self.img], x=[self.p], y=[self.p], dw=[self.q-self.p], dh=[self.q-self.p], palette=bokehpalette, dilate=True)
blt.show(f)
Plot JuliaSet using matplotlib
In [4]:
j = JuliaSetPlot(-1.037 + .17j, -2, 2)
%time j.set_spacing(0.005)
%time j.generate()
%time j.show()
Plot JuliaSet using Bokeh
In [120]:
j = JuliaSetPlot(-1.037 + .17j, -2, 2)
%time j.set_spacing(0.005)
%time j.generate()
%time j.interact()
In [ ]:
In [ ]: