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 Complexity and Computation, a book about
2
exploring complexity science with Python. Available free from
3
4
http://greenteapress.com/complexity
5
6
Copyright 2016 Allen Downey
7
MIT License: http://opensource.org/licenses/MIT
8
"""
9
from __future__ import print_function, division
10
11
import sys
12
13
import numpy as np
14
import matplotlib.pyplot as plt
15
from matplotlib import animation
16
17
"""
18
For animation to work in the notebook, you might have to install
19
ffmpeg. On Ubuntu and Linux Mint, the following should work.
20
21
sudo add-apt-repository ppa:mc3man/trusty-media
22
sudo apt-get update
23
sudo apt-get install ffmpeg
24
"""
25
26
from Cell2D import Cell2D, Cell2DViewer
27
from scipy.signal import correlate2d
28
29
30
class Life(Cell2D):
31
"""Implementation of Conway's Game of Life."""
32
kernel = np.array([[1, 1, 1],
33
[1,10, 1],
34
[1, 1, 1]])
35
36
table = np.zeros(20, dtype=np.uint8)
37
table[[3, 12, 13]] = 1
38
39
def step(self):
40
"""Executes one time step."""
41
c = correlate2d(self.array, self.kernel, mode='same')
42
self.array = self.table[c]
43
44
45
class LifeViewer(Cell2DViewer):
46
"""Viewer for Game of Life."""
47
48
49
def main(script, *args):
50
"""Constructs a puffer train.
51
52
Uses the entities in this file:
53
http://www.radicaleye.com/lifepage/patterns/puftrain.lif
54
"""
55
lwss = [
56
'0001',
57
'00001',
58
'10001',
59
'01111'
60
]
61
62
bhep = [
63
'1',
64
'011',
65
'001',
66
'001',
67
'01'
68
]
69
70
n = 400
71
m = 600
72
life = Life(n, m)
73
74
col = 120
75
life.add_cells(n//2+12, col, *lwss)
76
life.add_cells(n//2+26, col, *lwss)
77
life.add_cells(n//2+19, col, *bhep)
78
viewer = LifeViewer(life)
79
anim = viewer.animate(frames=100, interval=1)
80
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99)
81
plt.show()
82
83
84
if __name__ == '__main__':
85
main(*sys.argv)
86
87
88
89