📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Code example from Think Complexity, by Allen Downey.12Copyright 2016 Allen Downey3MIT License: http://opensource.org/licenses/MIT4"""5from __future__ import print_function, division67import numpy as np8import matplotlib.pyplot as plt9import matplotlib.animation as animation10from scipy.signal import convolve2d1112def add_cells(x, y, *strings):13"""Adds cells at the given location.1415x: left coordinate16y: top coordinate17strings: list of strings of 0s and 1s18"""19for i, s in enumerate(strings):20a[y+i, x:x+len(s)] = np.array([int(b) for b in s])2122# the starting patterns23lwss = [24'0001',25'00001',26'10001',27'01111'28]2930bhep = [31'1',32'011',33'001',34'001',35'01'36]3738# add up the neighbors and get 10 points if the middle is live39kernel = np.array([[1, 1, 1],40[1,10, 1],41[1, 1, 1]], dtype=np.uint8)4243# the cell is live if the total is 3, 12, or 1344table = np.zeros(20, dtype=np.uint8)45table[[3, 12, 13]] = 14647# make the array48n = 20049m = 60050a = np.zeros((n, m), np.uint8)5152# add the initial patterns53x = 10054add_cells(x, n//2-8, *lwss)55add_cells(x, n//2+6, *lwss)56add_cells(x, n//2-1, *bhep)5758# draw the initial state59fig = plt.figure()60cmap = plt.get_cmap('Greens')61im = plt.imshow(a, cmap=cmap, interpolation='nearest')62plt.xticks([])63plt.yticks([])6465# animate the rest66def animate_func(i):67"""Draws one frame of the animation."""68global a69c = convolve2d(a, kernel, mode='same')70a = table[c]71im.set_array(a)72return im,7374anim = animation.FuncAnimation(fig, animate_func, frames=100, interval=0)75plt.show()767778