📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Code from Think Complexity, 2nd Edition, by Allen Downey.12Available from http://greenteapress.com34Copyright 2016 Allen B. Downey.5MIT License: https://opensource.org/licenses/MIT6"""78import numpy as np9import matplotlib.pyplot as plt101112def make_table(rule):13"""Makes the CA table for a given rule.1415rule: integer 0-2551617returns: NumPy array of uint818"""19rule = np.array([rule], dtype=np.uint8)20table = np.unpackbits(rule)[::-1]21return table222324def print_table(table):25"""Prints the rule table in LaTeX format."""26print('\\beforefig')27print('\\centerline{')28print('\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}')29print('\\hline')3031res = ['prev'] + ['{0:03b}'.format(i) for i in range(8)]32print(' & '.join(res) + ' \\\\ \n\\hline')3334res = ['next'] + [str(x) for x in table]35print(' & '.join(res) + ' \\\\ \n\\hline')3637print('\\end{tabular}}')383940class Cell1D:41"""Represents a 1-D a cellular automaton"""4243def __init__(self, rule, n, m=None):44"""Initializes the CA.4546rule: integer47n: number of rows48m: number of columns4950Attributes:51table: rule dictionary that maps from triple to next state.52array: the numpy array that contains the data.53next: the index of the next empty row.54"""55self.table = make_table(rule)56self.n = n57self.m = 2*n + 1 if m is None else m5859self.array = np.zeros((n, self.m), dtype=np.int8)60self.next = 06162def start_single(self):63"""Starts with one cell in the middle of the top row."""64self.array[0, self.m//2] = 165self.next += 16667def start_random(self):68"""Start with random values in the top row."""69self.array[0] = np.random.random(self.m).round()70self.next += 17172def start_string(self, s):73"""Start with values from a string of 1s and 0s."""74# TODO: Check string length75self.array[0] = np.array([int(x) for x in s])76self.next += 17778def loop(self, steps=1):79"""Executes the given number of time steps."""80for i in range(steps):81self.step()8283def step(self):84"""Executes one time step by computing the next row of the array."""85a = self.array86i = self.next87window = [4, 2, 1]88c = np.correlate(a[i-1], window, mode='same')89a[i] = self.table[c]90self.next += 19192def draw(self, start=0, end=None):93"""Draws the CA using pyplot.imshow.9495start: index of the first column to be shown96end: index of the last column to be shown97"""98a = self.array[:, start:end]99plt.imshow(a, cmap='Blues', alpha=0.7)100101# turn off axis tick marks102plt.xticks([])103plt.yticks([])104105106def draw_ca(rule, n=32):107"""Makes and draw a 1D CA with a given rule.108109rule: int rule number110n: number of rows111"""112ca = Cell1D(rule, n)113ca.start_single()114ca.loop(n-1)115ca.draw()116117118