Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132927 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 2011 Allen B. Downey.
7
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
8
"""
9
10
import numpy
11
12
import CADrawer
13
from CA import CA
14
15
16
class CircularCA(CA):
17
"""A variation of CA that wraps around so that the cells are
18
arranged in a ring.
19
"""
20
def __init__(self, rule, n=100, ratio=2):
21
"""n, m are the number of rows, columns.
22
array is the numpy array that contains the data.
23
next is the index of the next empty row.
24
"""
25
self.table = self.make_table(rule)
26
self.n = n
27
# allocate two extra cells for ghosts
28
self.m = ratio*n + 1 + 2
29
self.array = numpy.zeros((self.n, self.m), dtype=numpy.int8)
30
self.next = 0
31
32
def start_single(self):
33
"""start with one cell in the left of the top row"""
34
self.array[0, 1] = 1
35
self.next += 1
36
37
def step(self):
38
"""Executes one time step by computing the next row of the array."""
39
i = self.next
40
self.next += 1
41
42
a = self.array
43
t = self.table
44
45
# copy the ghost cells
46
a[i-1,0] = a[i-1,self.m-2]
47
a[i-1,self.m-1] = a[i-1,1]
48
49
for j in xrange(1,self.m-1):
50
a[i,j] = t[tuple(a[i-1, j-1:j+2])]
51
52
def get_array(self, start=0, end=None):
53
"""get a slice of columns from the CA, with slice indices
54
(start, end). We need to add one to avoid ghost cells.
55
"""
56
if end==None:
57
return self.array[:, start+1:self.m-1]
58
else:
59
return self.array[:, start+1:end+1]
60
61
62
def main(script, rule=30, n=100, *args):
63
rule = int(rule)
64
n = int(n)
65
66
ca = CircularCA(rule, n)
67
68
if 'random' in args:
69
ca.start_random()
70
else:
71
ca.start_single()
72
73
ca.loop(n-1)
74
75
if 'eps' in args:
76
drawer = CADrawer.EPSDrawer()
77
elif 'pil' in args:
78
drawer = CADrawer.PILDrawer()
79
else:
80
drawer = CADrawer.PyplotDrawer()
81
82
if 'trim' in args:
83
drawer.draw(ca, start=n/2, end=3*n/2+1)
84
else:
85
drawer.draw(ca)
86
87
drawer.show()
88
89
90
if __name__ == '__main__':
91
import sys
92
main(*sys.argv)
93
94