## Visualizing Attractors

An [attractor](https://en.wikipedia.org/wiki/Attractor#Strange_attractor) is a set of values to which a numerical system tends to evolve. An attractor is called a [strange attractor](https://en.wikipedia.org/wiki/Attractor#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&aacute;zaro Alonso](https://lazarusa.github.io/Webpage/codepython2.html), [François Pacull](https://aetperf.github.io/2018/08/29/Plotting-Hopalong-attractor-with-Datashader-and-Numba.html), [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors), [Paul Bourke](http://paulbourke.net/fractals/), and [James A. Bednar](http://github.io/jbednar).


## Clifford Attractors

For example, a [Clifford Attractor](http://paulbourke.net/fractals/clifford) 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)_:

\begin{equation}
x_{n +1} = \sin(a y_{n}) + c \cos(a x_{n})\\
y_{n +1} = \sin(b x_{n}) + d \cos(b y_{n})
\end{equation}

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](http://numba.pydata.org). First, we define the iterative attractor equation:


```python
import numpy as np, pandas as pd, datashader as ds
from datashader import transfer_functions as tf
from datashader.colors import inferno, viridis
from numba import jit
from math import sin, cos, sqrt, fabs

@jit
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.


```python
n=10000000

@jit
def trajectory(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 pd.DataFrame(dict(x=x,y=y))
```


```python
%%time
df = trajectory(Clifford, 0, 0, -1.3, -1.3, -1.8, -1.9)
```


```python
df.tail()
```

We can now aggregate these 10,000,000 continuous coordinates into a discrete 2D rectangular grid with [Datashader](http://datashader.org), counting each time a point fell into that grid cell:


```python
%%time

cvs = ds.Canvas(plot_width = 700, plot_height = 700)
agg = cvs.points(df, 'x', 'y')
print(agg.values[190:195,190:195],"\n")
```

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:


```python
ds.transfer_functions.Image.border=0

tf.shade(agg, cmap = ["white", "black"])
```

As you can see, the most-visited areas of the plane have an interesting structure for this set of parameters. To explore further, let's wrap up the above aggregation and shading commands into a function so we can apply them more easily:


```python
def dsplot(fn, vals, n=n, cmap=viridis, label=True):
    """Return a Datashader image by collecting `n` trajectory points for the given attractor `fn`"""
    lab = ("{}, "*(len(vals)-1)+" {}").format(*vals) if label else None
    df  = trajectory(fn, *vals, n=n)
    cvs = ds.Canvas(plot_width = 300, plot_height = 300)
    agg = cvs.points(df, 'x', 'y')
    img = tf.shade(agg, cmap=cmap, name=lab)
    return img
```

And let's load some colormaps that we can use for subsequent plots:


```python
from colorcet import palette
palette["viridis"]=viridis
palette["inferno"]=inferno
```

We can now use these colormaps with a pre-selected set of Clifford attractor parameter values (stored in a separate [YAML-format text file](https://raw.githubusercontent.com/pyviz/datashader/master/examples/topics/attractors.yml)) to show a wide variety of trajectories that these equations can form:


```python
import yaml
vals = yaml.load(open("attractors.yml","r"))

def args(name):
    """Return a list of available argument lists for the given type of attractor"""
    return [v[1:] for v in vals if v[0]==name]  

def plot(fn, vals=None, **kw):
    """Plot the given attractor `fn` once per provided set of arguments."""
    vargs=args(fn.__name__) if vals is None else vals
    return tf.Images(*[dsplot(fn, v[1:], cmap=palette[v[0]][::-1], **kw) for v in vargs]).cols(4)
```


```python
plot(Clifford)
```

Here the values shown are the arguments for the first call to `Clifford(x, y, a, b, c, d)`, with each subsequent call using the _x,y_ location of the previous call.  

Randomly sampling the parameter space typically yields much less dramatic patterns, such as all trajectory locations being on a small number of points:


```python
import numpy.random
numpy.random.seed(21)
num = 4

rvals=np.c_[np.zeros((num,2)), numpy.random.random((num,4))*4-2]
plot(Clifford, vals=[["kbc"]+list(rvals[i]) for i in range(len(rvals))], label=True)
```

If you wish, Datashader could easily be used to filter out such uninteresting examples, by applying a criterion to the aggregate array before shading and showing only those that remain (e.g. rejecting those where 80% of the pixel bins are empty).


## De Jong attractors

A variety of other sets of attractor equations have been proposed, such as these from [Peter de Jong](http://paulbourke.net/fractals/peterdejong):


```python
@jit
def De_Jong(x, y, a, b, c, d, *o):
    return sin(a * y) - cos(b * x), \
           sin(c * x) - cos(d * y)

plot(De_Jong)
```

## Svensson attractors

From [Johnny Svensson](http://paulbourke.net/fractals/peterdejong/):


```python
@jit
def Svensson(x, y, a, b, c, d, *o):
    return d * sin(a * x) - sin(b * y), \
           c * cos(a * x) + cos(b * y)

plot(Svensson)
```

## Bedhead Attractor

From [Ivan Emrich](https://www.deviantart.com/jaguarfacedman) and [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors):


```python
@jit
def Bedhead(x, y, a, b, *o):
    return sin(x*y/b)*y + cos(a*x-y), \
           x + sin(y)/b

plot(Bedhead)
```

## Fractal Dream Attractor

From Clifford A. Pickover's book “Chaos In Wonderland”, with parameters from [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors):


```python
@jit
def Fractal_Dream(x, y, a, b, c, d, *o):
    return sin(y*b)+c*sin(x*b), \
           sin(x*a)+d*sin(y*a)

plot(Fractal_Dream)
```

## Hopalong attractors

From Barry Martin, here with code for two variants from [François Pacull](https://aetperf.github.io/2018/08/29/Plotting-Hopalong-attractor-with-Datashader-and-Numba.html):


```python
@jit
def Hopalong1(x, y, a, b, c, *o):
    return y - sqrt(fabs(b * x - c)) * np.sign(x), \
           a - x
@jit
def Hopalong2(x, y, a, b, c, *o):
    return y - 1.0 - sqrt(fabs(b * x - 1.0 - c)) * np.sign(x - 1.0), \
           a - x - 1.0

plot(Hopalong1)
```


```python
plot(Hopalong2)
```

##  Gumowski-Mira Attractor

From [I. Gumowski and C. Mira](http://kgdawiec.bplaced.net/badania/pdf/cacs_2010.pdf), with code and parameters from [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors) and [L&aacute;zaro Alonso](https://lazarusa.github.io/Webpage/codepython2.html):


```python
@jit
def G(x, mu):
    return mu * x + 2 * (1 - mu) * x**2 / (1.0 + x**2)

@jit
def Gumowski_Mira(x, y, a, b, mu, *o):
    xn = y + a*(1 - b*y**2)*y  +  G(x, mu)
    yn = -x + G(xn, mu)
    return xn, yn

plot(Gumowski_Mira)
```

##  Symmetric Icon Attractor

The Hopalong and Gumowski-Mira equations often result in symmetric patterns, but a different approach is to *force* the patterns to be symmetric, which is often pleasing. Examples from “Symmetry in Chaos” by Michael Field and Martin Golubitsky, with code and parameters from [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors):


```python
@jit
def Symmetric_Icon(x, y, a, b, g, om, l, d, *o):
    zzbar = x*x + y*y
    p = a*zzbar + l
    zreal, zimag = x, y
    
    for i in range(1, d-1):
        za, zb = zreal * x - zimag * y, zimag * x + zreal * y
        zreal, zimag = za, zb
    
    zn = x*zreal - y*zimag
    p += b*zn
    
    return p*x + g*zreal - om*y, \
           p*y - g*zimag + om*x

plot(Symmetric_Icon)
```

## Interactive plotting

If you are running a live Python process, you can use Datashader with HoloViews and Bokeh to zoom in and see the individual steps in any of these calculations:


```python
import holoviews as hv
from holoviews.operation.datashader import datashade, dynspread
hv.extension('bokeh')

dynspread(datashade(hv.Points(trajectory(Clifford, *(args("Clifford")[5][1:]))), 
                    cmap=viridis[::-1]).opts(width=400,height=400))
```

Each time you zoom in in a live process, the data will be reaggregated, which should take a small fraction of a second for 10 million points.  Eventually, once you zoom in enough you should see individual data points, as we are not connecting the points into a trajectory here. 

You can also try "connecting the dots", which will reveal how the particle jumps discretely from one region of the space to another:


```python
dynspread(datashade(hv.Path([trajectory(Clifford, *(args("Clifford")[5][1:]))]), 
                    cmap=viridis[::-1]).opts(width=400,height=400))
```

Again, if you zoom in on a live server, the plot will update so that you can see the individual traces involved. 

On the live server, you can also explore to find your own parameter values that generate interesting patterns:


```python
def hv_clif(a,b,c,d,x0=0,y0=0,n=n):
    return datashade(hv.Points(trajectory(Clifford, x0, y0, a, b, c, d, n)), 
                     cmap=inferno[::-1], dynamic=False)

x0,y0,a,b,c,d = args("Clifford")[6][1:]

dm = hv.DynamicMap(hv_clif, kdims=['a', 'b', 'c', 'd'])
dm = dm.redim.range(a=(-2.0, 2.0), b=(-2.0,2.0), c=(-2.0,2.0), d=(-2.0,2.0))
dm = dm.redim.default(a=a, b=b, c=c, d=d).opts(width=500,height=500)
dm
```

Although many of the regions of this four-dimensional parameter space generate uninteresting trajectories such as single points, you can find interesting regions by starting with one of the _a,b,c,d_ tuples of values in previous plots, then click on one slider and use the left and right arrow keys to see how the plot changes as that parameter changes.

a197035bf3727f08c905831b619b0d5e0e2657e5
ipynb
Jupyter Notebook
examples/topics/strange_attractors.ipynb
av-fti/datashade_av
53bbffb85bcb33dbb9e6c15c73599eb146105967
BSD-3-Clause
examples/topics/strange_attractors.ipynb
av-fti/datashade_av
53bbffb85bcb33dbb9e6c15c73599eb146105967
BSD-3-Clause
examples/topics/strange_attractors.ipynb
av-fti/datashade_av
53bbffb85bcb33dbb9e6c15c73599eb146105967
BSD-3-Clause
2019-07-24T09:01:16.000Z
2019-07-24T09:01:16.000Z
Qwen/Qwen-72B
1. YES
2. YES