📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Code example from Complexity and Computation, a book about1exploring complexity science with Python. Available free from23http://greenteapress.com/complexity45Copyright 2011 Allen B. Downey.6Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.7"""89import numpy1011import CADrawer12from CA import CA131415class CircularCA(CA):16"""A variation of CA that wraps around so that the cells are17arranged in a ring.18"""19def __init__(self, rule, n=100, ratio=2):20"""n, m are the number of rows, columns.21array is the numpy array that contains the data.22next is the index of the next empty row.23"""24self.table = self.make_table(rule)25self.n = n26# allocate two extra cells for ghosts27self.m = ratio*n + 1 + 228self.array = numpy.zeros((self.n, self.m), dtype=numpy.int8)29self.next = 03031def start_single(self):32"""start with one cell in the left of the top row"""33self.array[0, 1] = 134self.next += 13536def step(self):37"""Executes one time step by computing the next row of the array."""38i = self.next39self.next += 14041a = self.array42t = self.table4344# copy the ghost cells45a[i-1,0] = a[i-1,self.m-2]46a[i-1,self.m-1] = a[i-1,1]4748for j in xrange(1,self.m-1):49a[i,j] = t[tuple(a[i-1, j-1:j+2])]5051def get_array(self, start=0, end=None):52"""get a slice of columns from the CA, with slice indices53(start, end). We need to add one to avoid ghost cells.54"""55if end==None:56return self.array[:, start+1:self.m-1]57else:58return self.array[:, start+1:end+1]596061def main(script, rule=30, n=100, *args):62rule = int(rule)63n = int(n)6465ca = CircularCA(rule, n)6667if 'random' in args:68ca.start_random()69else:70ca.start_single()7172ca.loop(n-1)7374if 'eps' in args:75drawer = CADrawer.EPSDrawer()76elif 'pil' in args:77drawer = CADrawer.PILDrawer()78else:79drawer = CADrawer.PyplotDrawer()8081if 'trim' in args:82drawer.draw(ca, start=n/2, end=3*n/2+1)83else:84drawer.draw(ca)8586drawer.show()878889if __name__ == '__main__':90import sys91main(*sys.argv)929394