-
Notifications
You must be signed in to change notification settings - Fork 668
/
Copy pathCell2D.py
95 lines (74 loc) · 2.57 KB
/
Cell2D.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
""" Code example from Complexity and Computation, a book about
exploring complexity science with Python. Available free from
http://greenteapress.com/complexity
Copyright 2016 Allen Downey
MIT License: http://opensource.org/licenses/MIT
"""
import numpy as np
import matplotlib.pyplot as plt
# Here's how animate works
# https://stackoverflow.com/questions/24816237/ipython-notebook-clear-cell-output-in-code
# https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.clear_output
from time import sleep
from IPython.display import clear_output
from utils import underride
class Cell2D:
"""Parent class for 2-D cellular automata."""
def __init__(self, n, m=None):
"""Initializes the attributes.
n: number of rows
m: number of columns
"""
m = n if m is None else m
self.array = np.zeros((n, m), np.uint8)
def add_cells(self, row, col, *strings):
"""Adds cells at the given location.
row: top row index
col: left col index
strings: list of strings of 0s and 1s
"""
for i, s in enumerate(strings):
self.array[row+i, col:col+len(s)] = np.array([int(b) for b in s])
def loop(self, iters=1):
"""Runs the given number of steps."""
for i in range(iters):
self.step()
def draw(self, **options):
"""Draws the array.
"""
draw_array(self.array, **options)
def animate(self, frames, interval=None, step=None):
"""Animate the automaton.
frames: number of frames to draw
interval: time between frames in seconds
iters: number of steps between frames
"""
if step is None:
step = self.step
plt.figure()
try:
for i in range(frames-1):
self.draw()
plt.show()
if interval:
sleep(interval)
step()
clear_output(wait=True)
self.draw()
plt.show()
except KeyboardInterrupt:
pass
def draw_array(array, **options):
"""Draws the cells."""
n, m = array.shape
options = underride(options,
cmap='Greens',
alpha=0.7,
vmin=0, vmax=1,
interpolation='none',
origin='upper',
extent=[0, m, 0, n])
plt.axis([0, m, 0, n])
plt.xticks([])
plt.yticks([])
return plt.imshow(array, **options)