Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132922 views
License: OTHER
1
""" Code example from Think Complexity, by Allen Downey.
2
3
Copyright 2016 Allen Downey
4
MIT License: http://opensource.org/licenses/MIT
5
"""
6
from __future__ import print_function, division
7
8
import numpy as np
9
import matplotlib.pyplot as plt
10
import matplotlib.animation as animation
11
from scipy.signal import convolve2d
12
13
def add_cells(x, y, *strings):
14
"""Adds cells at the given location.
15
16
x: left coordinate
17
y: top coordinate
18
strings: list of strings of 0s and 1s
19
"""
20
for i, s in enumerate(strings):
21
a[y+i, x:x+len(s)] = np.array([int(b) for b in s])
22
23
# the starting patterns
24
lwss = [
25
'0001',
26
'00001',
27
'10001',
28
'01111'
29
]
30
31
bhep = [
32
'1',
33
'011',
34
'001',
35
'001',
36
'01'
37
]
38
39
# add up the neighbors and get 10 points if the middle is live
40
kernel = np.array([[1, 1, 1],
41
[1,10, 1],
42
[1, 1, 1]], dtype=np.uint8)
43
44
# the cell is live if the total is 3, 12, or 13
45
table = np.zeros(20, dtype=np.uint8)
46
table[[3, 12, 13]] = 1
47
48
# make the array
49
n = 200
50
m = 600
51
a = np.zeros((n, m), np.uint8)
52
53
# add the initial patterns
54
x = 100
55
add_cells(x, n//2-8, *lwss)
56
add_cells(x, n//2+6, *lwss)
57
add_cells(x, n//2-1, *bhep)
58
59
# draw the initial state
60
fig = plt.figure()
61
cmap = plt.get_cmap('Greens')
62
im = plt.imshow(a, cmap=cmap, interpolation='nearest')
63
plt.xticks([])
64
plt.yticks([])
65
66
# animate the rest
67
def animate_func(i):
68
"""Draws one frame of the animation."""
69
global a
70
c = convolve2d(a, kernel, mode='same')
71
a = table[c]
72
im.set_array(a)
73
return im,
74
75
anim = animation.FuncAnimation(fig, animate_func, frames=100, interval=0)
76
plt.show()
77
78