Case Study: Cellular automata

Chapter 2
Case Study: Cellular automata
2.1
Introduction
Cellular automata are iterated functions that operate on a checkerboard-like discretized domain, typically
in the form of a one- or two-dimensional array. Each element of the array is described by a state that
can take on one of a finite number of values, for example 0 or 1:
0
1
P=
1
1
1
1
1
0
0
1
0
0
0
0
0
1
(2.1)
The function that determines the overall behavior of the system operates in a discrete-time manner, where
all of the states in the array are updated simultaneously according to the function with each iteration
- think of taking a picture of the entire array, and using that fixed representation of all the states to
determine all of the array element states at the next time step. We see that this behavior is quite a bit
different from lattice Monte Carlo simulations, where in each iteration of the Monte Carlo simulation, a
random array element is chosen and updated immediately based on the function governing the system’s
behavior.
Put another way, cellular automata can be thought of as representing a spatially distributed population
that evolves forward in time in a discrete manner - each iteration may represent the change producing
the next generation of matrix elements depending on each element’s previous state together with the
states of the previous generation’s neighbors.
While models of this form may appear to be gross simplifications of what truly takes place in a real physical
system, the remarkable characteristic of cellular automata is their ability to mimic the appearance of
spatial patterns and complicated dynamical behavior found in many natural systems. It is the appearance
of complicated spatio-temporal patterns from a homogenous grid and functions described by a small
number of simple rules that has resulted in the widespread study of these systems [6].
43
44
CHAPTER 2. CASE STUDY: CELLULAR AUTOMATA
2.2
Some representative rules
We now consider two different sets of rules: Majority Rule and the Game of Life.
2.2.1
Majority Rule
In the 2008 United States primary elections, US voters become much more aware of how a caucus
functions and the importance group dynamics may play in the outcome of these election procedures.
As an extremely simple model of group behavior, consider a room full of voters choosing between two
candidates (candidate 0 and 1). Each voter Pi,j remains in their physical position through the entire
event and each voter is surrounded by eight neighbors. Therefore, the room can be considered an N × N
array of voters.
At periodic intervals, a vote of the entire population is taken, and each of these voting events constitutes
one generation of the iterative process. In between each vote, each person Pi,j discusses their current
choice of the two candidates with each of their neighbors: Pi−1,j−1 , Pi−1,j , Pi−1,j+1 , Pi,j−1 , Pi,j+1 ,
Pi+1,j−1 , Pi+1,j , and Pi+1,j+1 . After talking with each neighbor, voter Pi,j reconsiders their individual
choice with respect to the following rules (denoted collectively as function Rm ):
1. If the majority of neighbors is currently in favor of voter 0, the voter Pi,j switches their vote to
candidate 0 during the next vote:
0
0
0
1
1
0
0
1
0
→
0
0
0
1
0
0
0
1
0
2. If the majority of neighbors is currently in favor of voter 1, the voter Pi,j switches their vote to
candidate 1 during the next voting event:
1
1
1
1
0
0
0
1
0
→
1
1
1
1
1
0
3. if the neighbors are even split between the candidates, voter Pi,j
opinion.
0 1 0
0 1
1 0 1
1 0
→
0 1 0
0 1
2.2.2
0
1
0
does not change his or her current
0
1
0
The game of life
Now consider Conway’s Game of Life (denoted Lg ). In this example of cellular automata, we establish
an N × N grid as the physical domain that members populate and define the state of each grid element
(each population member) with a 0 to denote a dead member and a 1 to represent a live element. These
are the only states each element can take. Each generation (iteration) in the game evolves according to
the following set of rules:
2.2. SOME REPRESENTATIVE RULES
45
1. To simulate the support an element needs from society,
neighbors dies:
0 0 0
0
0 1 1
0
→
0 0 0
0
any live cell with fewer than two live
0
0
0
0
1
0
2. To model overcrowding effects, any live cell with more than three live neighbors dies:
1
1
0
0
1
1
0
1
0
1
1
0
→
0
0
1
0
1
0
3. Any live cell with two or three live neighbors lives unchanged to the next generation:
1
1
0
0
1
0
0
1
0
→
1
1
0
0
1
0
0
1
0
0
0
0
1
1
0
1
1
0
4. Any dead cell with three live neighbors comes to life:
0
0
0
2.2.3
1
0
0
1
1
0
→
Boundary conditions
When considering an element along one of the grid boundaries or in one of the four corners, we must
make some assumptions regarding the elements found outside the grid. There are at least two choices:
1. Zero-boundary conditions, where all elements outside the grid are assumed to be in state 0. For
the array (2.1):
0
0
0
P=
0
0
0
0
0
1
1
1
0
0
1
1
1
0
0
0
0
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
Rm (P)
→
0
1
1
0
0
1
1
0
0
0
0
0
0
0
0
0
(2.2)
We use double lines to separate the original P matrix from its new neighbors and illustrate the
effect of one iteration of majority rules Rm on the original array P under these boundary conditions.
In this case we see that a number of voters shifted support from 1 to 0, several remained committed
to candidate 1, and none changed their vote to 1.
2. Periodic boundary conditions, where the N × N population can be thought of as surrounded by
copies of itself - that the N × N population repeats in a checker-board pattern indefinitely in the
two dimensions in which it is defined. An alternative way of thinking about this is to visualize
taking the population array and bending it into a tube until the both outer edge columns meet.
46
CHAPTER 2. CASE STUDY: CELLULAR AUTOMATA
Then, the two open ends are bent in such a way that the ends of the tube meet, forming a torus
(mmm, donut). In this manner, a element on the edge of the domain is influenced by its immediate
neighbors inside the domain as well as the new neighbors that are formed from elements on the
opposite side of a domain.
We can efficiently construct the elements
rangement on nine copies of P, arranging
conditions:
1 1 0 0 1
0 0 1 0 0
0 1 1 1 0
P=
0 1 1 0 0
1 1 0 0 1
0 0 1 0 0
framing a N × N population by creating a tiled arthem in a 3 × 3 grid pattern to define the boundary
1
0
1
1
1
0
Rm (P)
→
1
1
1
1
1
1
1
0
0
0
0
0
0
0
1
0
(2.3)
Again, we use double lines to separate the original P matrix from its new neighbors. With one
iteration of majority rule we see the profound influence of the boundary conditions - many more
votes are preserved for candidate 1, and two are even created in this situation. We note that
periodic boundary conditions sometimes are used to approximate infinitely large domains, provided
the spatial structures that form in the N × N domain have scales significantly smaller that the “box
size” N.
2.3
Setting up the simulations
We now proceed with setting up a MATLAB simulation using the following strategy:
• Write a MATLAB function cafun.m main that
1. Takes as input an N × N array P corresponding to the initial states of the population (e.g.,
an array of randomly distributed 0’s and 1’s);
2. Sets up an outer loop m = 1:M corresponding to each generation of the population;
3. Creates a new array Q two rows and two columns larger than P containing a copy of P
“framed” by the appropriate boundary values;
4. Creates a set of nested loops (themselves nested inside the generation loop) i = 1:N, j =
1:N that is used to examine each Qi+1,j+1 in turn by creating a 3 × 3 subarray q of Q with
Qi+1,j+1 placed at the center of this subarray, surrounded by its eight neighbors;
5. Pass every one of the subarrays q to the appropriate rule function (lifefun.m or majorityfun.m)
to compute the updated value of Pi,j ;
6. After each Qi+1,j+1 is considered (thus updating each element of P to the next generation),
plot the result with function caplot.m.;
7. Move on to the next generation, incrementing m and saving the updated P in Psave (:, :, m)
• Create two functions lifefun.m and majorityfun.m that
1. Take as input a 3 × 3 array;
2. Check to make sure the array is the proper dimension and that the elements consist only of
0’s and/or 1’s;
2.4. SIMULATION SCRIPTS AND FUNCTIONS
47
3. Determine the number of nonzero and zero neighbors and the current state of the center
element;
4. Determine the new state of the center element according to the rules in use and return only
that state.
• and create a plot function caplot.m that
1. Takes as input the saved population array Psave ;
2. Plots the population as a grid of squares with white squares representing 0, black for 1;
3. Plots population density as a function of generation number.
2.4
2.4.1
Simulation scripts and functions
cafun.m
function [m,popdens] = cafun(P,M,bcflag,modelflag,plotdelay)
N = size(P,1);
if size(P,2) ~= N, error(’P must be square’), end
Psaved(:,:,1) = P; % used to store all generations
for m = 2:M % generation loop
[eqflag,popdens] = caplot(Psaved);
if eqflag, break, end % checks if at equilibrium
pause(plotdelay)
if bcflag == 0; % zero BCs - copy P and frame with 0s
Q = zeros(N+2);
Q(2:end-1,2:end-1) = P;
elseif bcflag == 1 % periodic BCs - 3x3 tile of P
Q = [P P P; P P P; P P P];
Q = Q(N:2*N+1,N:2*N+1); % cut out relevant section
end
for i = 1:N % row
for j = 1:N % column
q = Q(i:i+2,j:j+2); % 3x3 subarray
switch modelflag
case 0
P(i,j) = lifefun(q);
case 1
P(i,j) = majorityfun(q);
end
end % j loop
end % i loop
Psaved(:,:,m) = P;
end
The function above is the cellular automata main function; it takes as input P the initial state, M the
maximum number of generations, bcflag the boundary condition flag which is set to 0 for zero boundary
conditions, 1 for periodic boundary conditions, modelflag which is set to 0 for life, 1 for majority rule and
48
CHAPTER 2. CASE STUDY: CELLULAR AUTOMATA
plotdelay which defines the delay time for the plotting routine. The function returns the final generation
number reached and population density history. The two sets of rules (Life and Majority) are implemented
in the functions that follow.
2.4.2
lifefun.m
function centercell = lifefun(A)
% iterate a 3x3 array of 0’s and 1’s according to Conway’s game of life
if size(A) ~= [3 3], error(’Input must be 3x3’), end
totlive = nnz( find(A==1) );
totdead = nnz( find(A==0) );
if totlive+totdead ~= 9, error(’Array elements can only be 0 or 1’), end
% switch based on number of nonzero neighbors
switch totlive-A(2,2)
case {0 1}
centercell = 0; % cell dies
case 2
% no change
centercell = A(2,2);
case 3
centercell = 1; % birth or remains alive
case {4 5 6 7 8}
centercell = 0; % death by overcrowding
end
2.4.3
majorityfun.m
function centercell = majorityfun(A)
% iterate a 3x3 array of 0’s and 1’s according to majority rules
if size(A) ~= [3 3], error(’Input must be 3x3’), end
totlive = nnz( find(A==1) );
totdead = nnz( find(A==0) );
if totlive+totdead ~= 9, error(’Array elements can only be 0 or 1’), end
% switch based on number of nonzero neighbors
switch totlive-A(2,2);
case {0 1 2 3}
centercell = 0; % switch to 0
case 4
centercell = A(2,2); % tie - no change
case {5 6 7 8}
centercell = 1; % switch to 1
end
2.4. SIMULATION SCRIPTS AND FUNCTIONS
2.4.4
49
caplot.m
Finally, we present a function that plots the results of the simulation, both in terms of the current
population states and the time history of the population density. Note that we use the MATLAB imagesc
command instead of pcolor so that the state is displayed accurately as a rectangle color-coded to the
state of each element, whereas pcolor would display a (N − 1) × (N − 1) grid color field with the states
represented at the vertices of the grid and an interpolated color inside each element.
function [eqflag,livedens] = caplot(A)
% cellular automata plot
clf, subplot(2,2,1)
imagesc(1-A(:,:,end))
colormap gray, grid on
M = size(A,3); N = size(A,1);
for m = 1:M
livedens(m) = nnz(A(:,:,m))/(N*N);
end
subplot(2,2,2)
plot(livedens,’-o’)
axis([0 10*(1+floor(M/10)) 0 0.6])
grid on
xlabel(’Generation’)
ylabel(’Live site density’)
drawnow
% check for static or periodic state
eqflag = 0;
for m = M-1:-1:1
if A(:,:,end) == A(:,:,m)
Aper = mean(A(:,:,m+1:M),3); % avg over period
finaldens = nnz(Aper)/(N*N);
disp([’generation ’,int2str(m),’ equal to generation ’,int2str(M)])
disp([’final density: ’,num2str(finaldens)])
eqflag = 1;
end
end
2.4.5
Representative simulation results
We test both set of rules on a 50 × 50 grid initially set to a random state (note we set the random
number generator seed so that the results can be reproduced). Zero boundary conditions will be used in
both cases.
N = 50; bcflag = 0; plotdelay = 0
rand(’state’,1); P = round(rand(N));
The initial conditions are shown in Fig. 2.1. 20 iterations of the Game of Life are generated with the
following commands:
50
CHAPTER 2. CASE STUDY: CELLULAR AUTOMATA
Figure 2.1: Initial condition for the Game of Life and Majority Rule demonstrations.
M = 20;
modelflag = 0;
cafun(P,M,bcflag,modelflag,plotdelay)
Figure 2.2: Results of 20 iterations using the Game of Life rules and zero boundary conditions.
and the resulting population at m = 20 is shown in Fig. 2.2. Note how the population density drops
quickly initially. Likewise, 20 iterations of Majority Rule are generated with the following commands:
modelflag = 1;
figure(2)
cafun(P,M,bcflag,modelflag,plotdelay)
and the results are shown in Fig. 2.3. We see that the overall population does not change as dramatically
as with the Game of Life; the differences in the spatial patterns that develop in each also are striking.
2.5. REVIEW PROBLEMS
51
Figure 2.3: Results of 20 iterations using Majority Rule and zero boundary conditions.
2.5
Review problems
1. For a N ×N domain with N = 50, create representative plots of the number of live cells as a function
of generation number m for M = 150 total generations, both boundary conditions, random initial
conditions for Majority Rule.
2. Repeat previous problem for the Game of Life.
3. For the Game of Life, describe what happens for a N = 50 domain corresponding to an initial
condition of all zeros except for a (centered) row of ten consecutive live cells
4. For Majority Rule and both boundary conditions create plots of the number of generations required
to reach equilibrium (static or periodic) as a function of N for 3 ≤ N ≤ 20 is there any visible
trend?
5. Repeat previous problem for the Game of Life.
6. Modify the functions to allow for a new boundary condition for Majority Rule in which use as input
only the votes of neighbors inside the N × N population.