Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
1
""" Code from Think Complexity, 2nd Edition, by Allen Downey.
2
3
Available from http://greenteapress.com
4
5
Copyright 2016 Allen B. Downey.
6
MIT License: https://opensource.org/licenses/MIT
7
"""
8
9
import numpy as np
10
import matplotlib.pyplot as plt
11
12
13
def make_table(rule):
14
"""Makes the CA table for a given rule.
15
16
rule: integer 0-255
17
18
returns: NumPy array of uint8
19
"""
20
rule = np.array([rule], dtype=np.uint8)
21
table = np.unpackbits(rule)[::-1]
22
return table
23
24
25
def print_table(table):
26
"""Prints the rule table in LaTeX format."""
27
print('\\beforefig')
28
print('\\centerline{')
29
print('\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}')
30
print('\\hline')
31
32
res = ['prev'] + ['{0:03b}'.format(i) for i in range(8)]
33
print(' & '.join(res) + ' \\\\ \n\\hline')
34
35
res = ['next'] + [str(x) for x in table]
36
print(' & '.join(res) + ' \\\\ \n\\hline')
37
38
print('\\end{tabular}}')
39
40
41
class Cell1D:
42
"""Represents a 1-D a cellular automaton"""
43
44
def __init__(self, rule, n, m=None):
45
"""Initializes the CA.
46
47
rule: integer
48
n: number of rows
49
m: number of columns
50
51
Attributes:
52
table: rule dictionary that maps from triple to next state.
53
array: the numpy array that contains the data.
54
next: the index of the next empty row.
55
"""
56
self.table = make_table(rule)
57
self.n = n
58
self.m = 2*n + 1 if m is None else m
59
60
self.array = np.zeros((n, self.m), dtype=np.int8)
61
self.next = 0
62
63
def start_single(self):
64
"""Starts with one cell in the middle of the top row."""
65
self.array[0, self.m//2] = 1
66
self.next += 1
67
68
def start_random(self):
69
"""Start with random values in the top row."""
70
self.array[0] = np.random.random(self.m).round()
71
self.next += 1
72
73
def start_string(self, s):
74
"""Start with values from a string of 1s and 0s."""
75
# TODO: Check string length
76
self.array[0] = np.array([int(x) for x in s])
77
self.next += 1
78
79
def loop(self, steps=1):
80
"""Executes the given number of time steps."""
81
for i in range(steps):
82
self.step()
83
84
def step(self):
85
"""Executes one time step by computing the next row of the array."""
86
a = self.array
87
i = self.next
88
window = [4, 2, 1]
89
c = np.correlate(a[i-1], window, mode='same')
90
a[i] = self.table[c]
91
self.next += 1
92
93
def draw(self, start=0, end=None):
94
"""Draws the CA using pyplot.imshow.
95
96
start: index of the first column to be shown
97
end: index of the last column to be shown
98
"""
99
a = self.array[:, start:end]
100
plt.imshow(a, cmap='Blues', alpha=0.7)
101
102
# turn off axis tick marks
103
plt.xticks([])
104
plt.yticks([])
105
106
107
def draw_ca(rule, n=32):
108
"""Makes and draw a 1D CA with a given rule.
109
110
rule: int rule number
111
n: number of rows
112
"""
113
ca = Cell1D(rule, n)
114
ca.start_single()
115
ca.loop(n-1)
116
ca.draw()
117
118