#! /usr/bin/env python3 # def cellular_automaton ( step_num, cell_num ): import matplotlib.pyplot as plt import numpy as np # # Compute the entire X array. # x = np.zeros ( [ step_num + 1, cell_num ], dtype = int ) # # Set the initial condition in row 1. # mid = ( cell_num - 1 ) // 2 x[0,mid] = 1 # # Compute rows 0 through step_num by applying rule 30. # for i in range ( 1, step_num + 1 ): # # Compute columns 1 through cell_num-2 by applying rule 30. # (Leave first and last values at 0) # for j in range ( 1, cell_num - 1 ): if ( ( x[i-1,j-1] == 0 and x[i-1,j] == 0 and x[i-1,j+1] == 1 ) or \ ( x[i-1,j-1] == 0 and x[i-1,j] == 1 and x[i-1,j+1] == 0 ) or \ ( x[i-1,j-1] == 0 and x[i-1,j] == 1 and x[i-1,j+1] == 1 ) or \ ( x[i-1,j-1] == 1 and x[i-1,j] == 0 and x[i-1,j+1] == 0 ) ): x[i,j] = 1 # # Make a plot of red and white squares, with an outline. # plt.clf ( ) for i in range ( 0, step_num + 1 ): for j in range ( 0, cell_num ): if ( x[i,j] == 1 ): k = 'r' else: k = 'w' i2 = step_num - i plt.fill ( [ j, j+1, j+1, j ], [ i2, i2, i2+1, i2+1 ], color = k ) plt.plot ( [ j, j+1, j+1, j, j ], [ i2, i2, i2+1, i2+1, i2 ], 'k-' ) plt.axis ( 'off' ) plt.axis ( 'equal' ) filename = 'cellular_automaton.png' plt.savefig ( filename ) print ( ' Graphics saved as "' + filename + '"' ) plt.close ( ) return if ( __name__ == "__main__" ): step_num = 25 cell_num = 51 cellular_automaton ( step_num, cell_num )