# Visualizing Attractors#

An attractor is a set of values to which a numerical system tends to evolve. An attractor is called a strange attractor if the resulting pattern has a fractal structure. This notebook shows how to calculate and plot two-dimensional attractors of a variety of types, using code and parameters primarily from Lázaro Alonso, François Pacull, Jason Rampe, Paul Bourke, and James A. Bednar.

## Clifford Attractors#

For example, a Clifford Attractor is a strange attractor defined by two iterative equations that determine the x,y locations of discrete steps in the path of a particle across a 2D space, given a starting point (x0,y0) and the values of four parameters (a,b,c,d):

(1)#$$$x_{n +1} = \sin(a y_{n}) + c \cos(a x_{n})\\ y_{n +1} = \sin(b x_{n}) + d \cos(b y_{n})$$$

At each time step, the equations define the location for the following time step, and the accumulated locations show the areas of the 2D plane most commonly visited by the imaginary particle.

It’s easy to calculate these values in Python using Numba. First, we define the iterative attractor equation:

import numpy as np, pandas as pd, datashader as ds
from datashader import transfer_functions as tf
from numba import jit
from math import sin, cos, sqrt, fabs

@jit(nopython=True)
def Clifford(x, y, a, b, c, d, *o):
return sin(a * y) + c * cos(a * x), \
sin(b * x) + d * cos(b * y)

We then evaluate this equation 10 million times, creating a set of x,y coordinates visited. The @jit here and above is optional, but it makes the code 50x faster.

n=10000000

@jit(nopython=True)
def trajectory_coords(fn, x0, y0, a, b=0, c=0, d=0, e=0, f=0, n=n):
x, y = np.zeros(n), np.zeros(n)
x[0], y[0] = x0, y0
for i in np.arange(n-1):
x[i+1], y[i+1] = fn(x[i], y[i], a, b, c, d, e, f)
return x,y

def trajectory(fn, x0, y0, a, b=0, c=0, d=0, e=0, f=0, n=n):
x, y = trajectory_coords(fn, x0, y0, a, b, c, d, e, f, n)
return pd.DataFrame(dict(x=x,y=y))
%%time
df = trajectory(Clifford, 0, 0, -1.3, -1.3, -1.8, -1.9)
CPU times: user 1.28 s, sys: 236 ms, total: 1.52 s
Wall time: 1.52 s
df.tail()
x y
9999995 1.857884 1.395837
9999996 0.375264 -0.205512
9999997 -1.326024 -2.301316
9999998 0.423711 2.867012
9999999 -0.981134 1.060115

We can now aggregate these 10,000,000 continuous coordinates into a discrete 2D rectangular grid with Datashader, counting each time a point fell into that grid cell:

%%time

cvs = ds.Canvas(plot_width = 700, plot_height = 700)
agg = cvs.points(df, 'x', 'y')
print(agg.values[190:195,190:195],"\n")
[[ 37  41  26  24  24]
[ 28  30  42  27  26]
[111  53  29  37  28]
[145 177 113  63  44]
[ 78  94 136 140  96]]

CPU times: user 533 ms, sys: 11.9 ms, total: 545 ms
Wall time: 545 ms

A small portion of that grid is shown above, but it’s difficult to see the grid’s structure from the numerical values. To see the entire array at once, we can turn each grid cell into a pixel, using a greyscale value from white to black:

ds.transfer_functions.Image.border=0