📚 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 2016 Allen Downey6MIT License: http://opensource.org/licenses/MIT7"""89import numpy as np10import matplotlib.pyplot as plt1112# Here's how animate works13# https://stackoverflow.com/questions/24816237/ipython-notebook-clear-cell-output-in-code14# https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.clear_output1516from time import sleep17from IPython.display import clear_output1819from utils import underride202122class Cell2D:23"""Parent class for 2-D cellular automata."""2425def __init__(self, n, m=None):26"""Initializes the attributes.2728n: number of rows29m: number of columns30"""31m = n if m is None else m32self.array = np.zeros((n, m), np.uint8)3334def add_cells(self, row, col, *strings):35"""Adds cells at the given location.3637row: top row index38col: left col index39strings: list of strings of 0s and 1s40"""41for i, s in enumerate(strings):42self.array[row+i, col:col+len(s)] = np.array([int(b) for b in s])4344def loop(self, iters=1):45"""Runs the given number of steps."""46for i in range(iters):47self.step()4849def draw(self, **options):50"""Draws the array.51"""52draw_array(self.array, **options)5354def animate(self, frames, interval=None, step=None):55"""Animate the automaton.5657frames: number of frames to draw58interval: time between frames in seconds59iters: number of steps between frames60"""61if step is None:62step = self.step6364plt.figure()65try:66for i in range(frames-1):67self.draw()68plt.show()69if interval:70sleep(interval)71step()72clear_output(wait=True)73self.draw()74plt.show()75except KeyboardInterrupt:76pass777879def draw_array(array, **options):80"""Draws the cells."""81n, m = array.shape82options = underride(options,83cmap='Greens',84alpha=0.7,85vmin=0, vmax=1,86interpolation='none',87origin='upper',88extent=[0, m, 0, n])8990plt.axis([0, m, 0, n])91plt.xticks([])92plt.yticks([])9394return plt.imshow(array, **options)959697