Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 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
10
import numpy as np
11
import matplotlib.pyplot as plt
12
13
# Here's how animate works
14
# https://stackoverflow.com/questions/24816237/ipython-notebook-clear-cell-output-in-code
15
# https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.clear_output
16
17
from time import sleep
18
from IPython.display import clear_output
19
20
from utils import underride
21
22
23
class Cell2D:
24
"""Parent class for 2-D cellular automata."""
25
26
def __init__(self, n, m=None):
27
"""Initializes the attributes.
28
29
n: number of rows
30
m: number of columns
31
"""
32
m = n if m is None else m
33
self.array = np.zeros((n, m), np.uint8)
34
35
def add_cells(self, row, col, *strings):
36
"""Adds cells at the given location.
37
38
row: top row index
39
col: left col index
40
strings: list of strings of 0s and 1s
41
"""
42
for i, s in enumerate(strings):
43
self.array[row+i, col:col+len(s)] = np.array([int(b) for b in s])
44
45
def loop(self, iters=1):
46
"""Runs the given number of steps."""
47
for i in range(iters):
48
self.step()
49
50
def draw(self, **options):
51
"""Draws the array.
52
"""
53
draw_array(self.array, **options)
54
55
def animate(self, frames, interval=None, step=None):
56
"""Animate the automaton.
57
58
frames: number of frames to draw
59
interval: time between frames in seconds
60
iters: number of steps between frames
61
"""
62
if step is None:
63
step = self.step
64
65
plt.figure()
66
try:
67
for i in range(frames-1):
68
self.draw()
69
plt.show()
70
if interval:
71
sleep(interval)
72
step()
73
clear_output(wait=True)
74
self.draw()
75
plt.show()
76
except KeyboardInterrupt:
77
pass
78
79
80
def draw_array(array, **options):
81
"""Draws the cells."""
82
n, m = array.shape
83
options = underride(options,
84
cmap='Greens',
85
alpha=0.7,
86
vmin=0, vmax=1,
87
interpolation='none',
88
origin='upper',
89
extent=[0, m, 0, n])
90
91
plt.axis([0, m, 0, n])
92
plt.xticks([])
93
plt.yticks([])
94
95
return plt.imshow(array, **options)
96
97