Mercurial > public > think_complexity
comparison CircularCA.py @ 40:ae310a2f42b4
Create a circular cellular automaton for ch 6, exercise 1.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 12 Jan 2013 15:03:31 -0600 |
parents | |
children | 039249efe42f |
comparison
equal
deleted
inserted
replaced
39:49db586c727a | 40:ae310a2f42b4 |
---|---|
1 """Chapter 6, exercise 1 in Allen Downey's Think Complexity book. | |
2 | |
3 "Create a new class called CircularCA that extends CA so that the cells are | |
4 arranged in a ring. Hint: you might find it useful to add a column of 'ghost | |
5 cells' to the array." | |
6 | |
7 """ | |
8 | |
9 import numpy | |
10 | |
11 from CA import CA | |
12 | |
13 | |
14 class CircularCA(CA): | |
15 """A circular cellular automaton; the cells are arranged in a ring.""" | |
16 | |
17 def __init__(self, rule, n=100, ratio=2): | |
18 """Parameters: | |
19 | |
20 * rule: an integer in the range 0-255 that represents the CA rule | |
21 using Wolfram's encoding | |
22 * n: the number of rows (time steps) in the result | |
23 * ratio: the ratio of columns to rows | |
24 | |
25 """ | |
26 self.table = self.make_table(rule) | |
27 self.n = n | |
28 # a ghost column is added to either end | |
29 self.m = ratio * n + 3 # add 2 ghost columns | |
30 self.array = numpy.zeros((n, self.m), dtype=numpy.int8) | |
31 self.next = 0 | |
32 | |
33 def start_single(self): | |
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 assert i > 0, 'call start_single() or start_random() first' | |
42 | |
43 a = self.array | |
44 t = self.table | |
45 | |
46 # update the ghost cells to enable wrapping | |
47 a[i - 1, 0] = a[i - 1, self.m - 2] | |
48 a[i - 1, self.m - 1] = a[i - 1, 1] | |
49 | |
50 for j in xrange(1, self.m - 1): | |
51 a[i, j] = t[tuple(a[i - 1, j-1:j+2])] | |
52 | |
53 | |
54 def get_array(self, start=0, end=None): | |
55 """Gets a slice of columns from the CA, with slice indices | |
56 (start, end). | |
57 | |
58 """ | |
59 # do not return the ghost columns | |
60 if end==None: | |
61 return self.array[:, start+1:self.m-1] | |
62 else: | |
63 return self.array[:, start+1:end+1] | |
64 | |
65 | |
66 if __name__ == '__main__': | |
67 | |
68 import sys | |
69 from CADrawer import PyplotDrawer | |
70 | |
71 def main(script, rule, n): | |
72 rule = int(rule) | |
73 n = int(n) | |
74 ca = CircularCA(rule, n) | |
75 ca.start_single() | |
76 ca.loop(n - 1) | |
77 | |
78 drawer = PyplotDrawer() | |
79 drawer.draw(ca) | |
80 drawer.show() | |
81 | |
82 | |
83 main(*sys.argv) |