Created
May 2, 2016 14:39
-
-
Save mattpap/e553df314c6091fb10955f8466822e1e to your computer and use it in GitHub Desktop.
Game of life in bokeh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Run `bin/bokeh serve` and in a new terminal run `python conway.py`. | |
# Based on https://github.com/thearn/game-of-life. | |
from bokeh.plotting import figure, curdoc | |
from bokeh.client import push_session | |
from numpy.fft import fft2, ifft2, fftshift | |
import numpy as np | |
def fft_convolve2d(x,y): | |
""" | |
2D convolution, using FFT | |
""" | |
fr = fft2(x) | |
fr2 = fft2(np.flipud(np.fliplr(y))) | |
m,n = fr.shape | |
cc = np.real(ifft2(fr*fr2)) | |
cc = np.roll(cc, - int(m / 2) + 1, axis=0) | |
cc = np.roll(cc, - int(n / 2) + 1, axis=1) | |
return cc | |
def conway(state, k=None): | |
""" | |
Conway's game of life state transition | |
""" | |
# set up kernel if not given | |
if k == None: | |
m, n = state.shape | |
k = np.zeros((m, n)) | |
k[m/2-1 : m/2+2, n/2-1 : n/2+2] = np.array([[1,1,1],[1,0,1],[1,1,1]]) | |
# computes sums around each pixel | |
b = fft_convolve2d(state,k).round() | |
c = np.zeros(b.shape) | |
c[np.where((b == 2) & (state == 1))] = 1 | |
c[np.where((b == 3) & (state == 1))] = 1 | |
c[np.where((b == 3) & (state == 0))] = 1 | |
# return new state | |
return c | |
if __name__ == "__main__": | |
m, n = 100, 100 | |
fig = figure(x_range=(0, n), y_range=(0, m)) | |
board = np.random.random(m*n).reshape((m, n)).round() | |
img = fig.image(image=[board], x=0, y=0, dw=n, dh=m, palette="Greys3") | |
session = push_session(curdoc()) | |
def cb(): | |
global board | |
board = conway(board) | |
img.data_source.data = dict(image=[board]) | |
curdoc().add_periodic_callback(cb, 100) | |
session.show(fig) | |
session.loop_until_closed() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That is fairly simple in getting the Bokeh related components together.