Cellular automata introduction

Cellular automata was originally proposed by Von Neumann in the 1950s to simulate the self-replication of biological cells. Cellular automata came to the attention of scientists in 1970 when John Holden Conway of Cambridge University designed a computer game called “The Game of Life”.

S. Wolram published a series of papers in 1983. In this paper, the models generated by 256 rules of elementary cellular machine are studied and their evolution is described by entropy. Cellular automata are classified into stationary, periodic, chaotic and complex types.

Cellular automata (CA) is a method used to simulate local rules and local connections. Cellular automata are typically defined on a grid, where each point represents a cell and a finite state. The change rule applies to each cell and simultaneously. The rules of change typically depend on the state of the cell and the state of its (4 or 8) neighbors.

Change rules for 3 cells & change rules for cell states typically depend on the state of a cell and the states of its (4 or 8) neighbors.

Application of cellular automata Cellular automata has been applied to physical simulation, biological simulation and other fields.

5 Cellular automata MATLAB programming combined with the above, we can understand cellular automata simulation needs to understand three points. One is cellular, which can be understood as a square block composed of one or more points in the matrix in MATLAB. Generally, we use a point in the matrix to represent a cellular. The second is the change rule. The change rule of cellular determines the state of cellular at the next moment. The third is the state of the cell. The state of the cell is self-defined and usually opposite, such as the living state or death state of the creature, the red light or the green light, the point with or without obstacles, and so on.

One dimensional cellular automata — traffic rulesDefinition: 6.1 Cells are distributed on a one-dimensional linear grid. 6.2 Cells have only two states: car and empty. Two-dimensional cellular automata — The Game of lifeDefinition: 7.1 Cells are distributed on a two-dimensional square grid. 7.2 Cells have only two states of life and death.The cellular state is determined by its eight neighbors. Rules:Skull: death; Smiley face: if there are three smiley faces around you, the middle will become smiley face less than two or more smiley faces, and the middle will become death.

What is cellular automata discrete system: cellular is defined in finite time and space, and the state of cellular is finite. Dynamical system: The behavior of cellular automata is characterized by dynamics. Simplicity and complexity: Cellular automata simulate complex worlds by controlling interacting cells with simple rules.

9 Constituent Elements (1) Cell Cell is the basic unit of cellular automata: state: Every cell has the function of memory storage state. Discrete: In the simple case, there are only two possible states of cellular; In more complex cases, cells have multiple states. Update: cellular states are constantly updated according to dynamic rules.(2) LatticeDifferent dimensional gridCommon two-dimensional grid (3) Neighborhood (4) Boundary Reflective: the state with itself as the boundary absorbing: regardless of the boundary (the car disappears when it reaches the boundary)

(5) Rules (State transition function)Definition: The dynamic function of the cellular state at the next moment is determined according to the current state of the cell and its neighbors. Simply speaking, it is a state transfer function. Classification: Summation type: the state of a cell depends on and only depends on the current state of all its neighbors and its own current state. Legal: The sum rule belongs to the legal rule. However, if the rules of cellular automata are limited to summation type, cellular automata will be limited.6. Forest fires Green: trees; Red: fire; Black: empty space. Tree: Becomes fire when there is fire around or when struck by lightning. Open space: with probability P into trees rational analysis: red for fire; Ash is empty space; Green is the treeThe sum of the three states of cell density is 1The density of fire to open space is equal to the density of open space to trees (new trees are equal to burned trees)F is the probability of lightning: much less than the probability of tree generation; T smax T_{smax}T smax is the time scale for a whole bunch of trees to burnProgram implementationPeriodic boundary condition purchasesThe numbers are numbered to construct the neighbor matrixThe numbers in the above matrix correspond to the upper neighbor numbers of the same position numbers of the original matrix, and 1 and 1 correspond to the same principle: (7) Transportation conceptDistance and densityFlow equationConservation equationSpacetime trajectory (horizontal axis is space and vertical axis is time)The intersection of the red line and the blue line indicates the position of the car at each time. If it’s a vertical line, it’s the time the car was in that position

Macro continuous model:The most commonly used rules:The red bar means the velocity is full.

1 Acceleration rule: do not exceed v max (2 grids /s) v_{Max} (2 grids /s) v Max (2 grids /s) 2 Collision prevention: do not exceed the vehicle distance

Theoretical analysis:Result analysis: density and flowThe first graph: the abscissa is the normalized density, and the ordinate is the traffic flow. Second figure: theoretical value versus CA result

Result analysis: space-time trajectoryThe dark area in the middle is a traffic jam.

Two, some source code


     %% NOTE

% Total runtime for this code was about 1- 3 minutes on the personal 
% computer used by the original researcher
% This runtime is expected to vary from device to device, and is being used 
% here to obtain a general comparison for runtime for the different
% models. It is not for a universal runtime value

%% Documentation

% n             size of each dimension of our square cellular automata grid
% P_HIV         fraction (probability) of cells initially infected by virus
% P_i           probability of a healthy cell becoming infected if its
%               neighborhood contains 1 I1 cell or X I2 cells
% P_v           probability of a healthy cell becoming infected by coming
%               in contact with a virus randomly (not from its
%               neighborhood)
% P_rep          Probability of a dead cell becoming replaced by a healthy
%               cell
% P_repI          Probability of a dead cell becoming replaced by an infected
%               cell
% X             Number of I2 cells in the neighborhood of an H cell that
%               can cause it to become infected
% tau1          tau1 is the number of timesteps it takes for an acute
%               infected cell to become latent.
% tau2          tau2 is the number of timesteps it takes for a latent
%               infected cell to become dead.
% totalsteps    totalsteps is the total number of steps of the CA (the % total number of weeks of simulations)
% grid          our cellular automata (CA) grid
% tempgrid      tempgrid is a temporary grid full of random numbers that is
%               used to randomly add different states to our CA grid.
% taugrid       taugrid is a grid the same size as our CA grid that stores
%               the number of timesteps that a cell has been in state I_1.
%               If the number reaches tau1, then the state changes to I_2.
% state         state is a [5 x totalsteps] size matrix that stores
%               the total number of cells in each state at each timestep
%               and the last row stores sum of I_1 and I_2 at each timestep
% timestep      each simulation step of the cellular automata
%               1 timestep = 1 week of time in the real world
% nextgrid      nextgrid is a temporary grid. It is a copy of the CA grid
%               from the previous simulation. It stores all the CA rule
%               updates of the current timestep and stores it all back to
%               the grid to display.

%% Clean-up

clc;            % clears command window
clear all;      % clears workspace and deletes all variables
close all;      % closes all open figures

%% Parameters

n = 100;            % meaning that our grid will have the dimensions n x n
P_HIV = 0.05;      % initial grid will have P_hiv acute infected cells
P_i = 0.997;        % probability of infection by neighbors
P_v = 0.00001;      % probability of infection by random viral contact
P_rep = 0.99;        % probability of dead cell being replaced by healthy
P_repI = 0.00001;     % probability of dead cell being replaced by infected
X = 4;              % there must be at least X I_2 neighbors to infect cell
tau1 = 4;           % time delay for I_1 cell to become I_2 cell
tau2 = 1;           % time delay for I_2 cell to become D cell
totalsteps = 600 ;  % total number of weeks of simulation to be performed
savesteps = [3 7 11 15 20 25 50 100 150 200 250 300 350 400 450 500]; 
                    %timesteps for which we want to save simulation image

%% States

% State 1: H:   Healthy          (Color- Green)
% State 4: I_1: Active Infected  (Color- Cyan)
% State 3: I_2: Latent Infected  (Color- Blue)
% State 2: D:   Dead             (Color- Black)

%% Initial Grid


grid = ones(n);     % creates our initial n x n matrix and fills all cells
% with value 1 (meaning H state - Healthy cell)
tempgrid = rand(n); % creates a grid of random values of the same size as
% our CA grid. Used to randomly add I_1 state to our grid
grid(tempgrid(:,:)<=P_HIV) = 4;  % I_1 state added with probability  P_HIV

% The following sets the edge values of the grid to H state
grid(:,1 n]) = 1;   % to set every value in the first and last column to 1
grid([1 n],:) = 1;   % to set every value in the first and last row to 1

% NOTE: Our CA only simulates from rows 2 to n- 1.and columns 2 to n1.
%       This is to prevent the edge row and column cells from having an
%       out-of-bounds error when checking the neighbors around them.
%       The edge values are all set to H state so that it does not affect
%       Rule 1 of the CA for cells next to them

% set(figure, 'OuterPosition'[100 30 740 740]) % sets figure window size
% % outerposition values are [left, bottom, width, height]
% print1(grid);   % prints the initial grid
% saveas(gcf,strcat('Model1Timestep0.pdf'));

%% Simulation

    nextgrid = grid;
    for x=2:n- 1
        for y=2:n- 1
            
            % Rule 1
            % If the cell is in H state and at least one of its neighbors
            % is in I_1 state, or X of its neighbors is in I_2 state, then
            % the cell becomes I_1 with a probability of P_i
            % The cell may also becomes I_1 by randomly coming in
            % contact with a virus from outside its neighborhood with a
            % probability of P_v
            if(grid(x,y)==1)
                if((rand<=P_i && (grid(x- 1,y- 1) = =4 || grid(x- 1,y)==4 || ...
                        grid(x- 1,y+1) = =4 || grid(x,y- 1) = =4 || ...
                        grid(x,y+1) = =4 || grid(x+1,y- 1) = =4 || ...
                        grid(x+1,y)==4 || grid(x+1,y+1) = =4 || ...
                        ((grid(x- 1,y- 1) = =3) + (grid(x- 1,y)==3) +... (grid(x- 1,y+1) = =3) + (grid(x,y- 1) = =3) +... (grid(x,y+1) = =3) + (grid(x+1,y- 1) = =3) +... (grid(x+1,y)==3) + (grid(x+1,y+1) = =3))>=X ))...
                        || rand<=P_v)                    
 
                end
     
            end
            
            % Rule 2
            % If the cell is in state I_1, and has been in this state for
            % tau1 timesteps, the cell becomes I_2 state (latent infected)
            if((grid(x,y)==4))
                taugrid(x,y) = taugrid(x,y)+1;
                if(taugrid(x,y)==tau1)
                    nextgrid(x,y)=3;
                    taugrid(x,y)=0;
                end
                continue;
            end
            
            % Rule 3
            % If the cell is in I_2 state, and has been in this state for
            % tau2 timesteps, the cell becomes D state (dead)
            % Since tau2=1.this rule is implemented every timestep
            if((grid(x,y)==3))
                nextgrid(x,y)=2;
                continue;
            end
            
            % Rule 4 a and b
            % If the cell is in D state, then the cell will become H state
            % with probability P_rep (4.a) or I_1 state with probability
            % P_repI (4.b)
            if(grid(x,y)==2 && rand<=P_rep)
                if(rand<=P_repI)
                    nextgrid(x,y)=4;
                    continue;
                else
                    nextgrid(x,y)=1;
                end
            end
            
        end
    end
    % to assign the updates of this timestep in nextgrid back to our grid
    grid=nextgrid;          
    % to display the grid at the end of each timestep
    print1(grid);
    % to save the image of the simulation every 25 timesteps as a pdf
    if(find(savesteps==timestep))
        saveas(gcf,strcat('Model1Timestep',num2str(timestep),'.pdf'));
    end
    
    state(1,timestep) = sum(sum(grid(2:n- 1.2:n- 1) = =1));
    state(2,timestep) = sum(sum(grid(2:n- 1.2:n- 1) = =2));
    state(3,timestep) = sum(sum(grid(2:n- 1.2:n- 1) = =3));
    state(4,timestep) = sum(sum(grid(2:n- 1.2:n- 1) = =4));
    
    timestep=timestep+1;    % to move to the next timestep
end

% The following lines of code are to display a graph of each state of
% cells during simulation
set(figure, 'OuterPosition'[200 100 700 500]) % sets figure window size
plot( 1:totalsteps , state(1, :).'g'.1:totalsteps , state(4, :).'c'.1:totalsteps , state(3, :).'b'.1:totalsteps , state(2, :).'k' , 'linewidth'.2 );
legend( 'Healthy'.'Acute Infected'.'Latent Infected'.'Dead'.'Location' ,'NorthEast' );
saveas(gcf,strcat('Model1GraphSingleRun.pdf'));
error(nargchk(1,Inf,nargin)) ;

% check the arguments
if ~isnumeric(x),
    error('Numeric argument expected'); endif nargin==1,
    y = [] ;
    va = [] ;
else
    va = varargin ;
    if ischar(va{1}),
        % optional arguments are
        y = [];elseif isnumeric(va{1})        
        y = va{1}; va = va(2:end) ;
    else
        error('Invalid second argument');end
    if mod(size(va),2) = =1,
        error('Property-Value have to be pairs'); end end % get the axes to plot in hca=get(get(0.'currentfigure'),'currentaxes');
if isempty(hca).warning('No current axes found') ;
    return ;
end

% get the current limits of the axis
% used for limit restoration later on
xlim = get(hca,'xlim'); ylim = get(hca,'ylim'); % setup datafor the vertical lines
xx1 = repmat(x(:). '.3.1); yy1 = repmat([ylim(:) ; nan],1,numel(x)) ;


Copy the code

3. Operation results

Matlab version and references

1 matlab version 2014A

2 Reference [1] CAI Limei. MATLAB Image Processing — Theory, Algorithm and Case Analysis [M]. Tsinghua University Press, 2020. [2] Yang Dan, ZHAO Haibin, LONG Zhe. Examples of MATLAB Image Processing In detail [M]. Tsinghua University Press, 2013. [3] Zhou Pin. MATLAB Image Processing and Graphical User Interface Design [M]. Tsinghua University Press, 2013. [4] LIU Chenglong. Proficient in MATLAB Image processing [M]. Tsinghua University Press, 2015. [5] MENG Yifan, LIU Yijun. [6] Zhang Na, Liu Kun, Han Meilin, Chen Chen. A PCA-SVM based Face Recognition Method [J]. Science and Technology Vision, 2021,(07) A face recognition algorithm based on PCA and LDA fusion [J]. Electronic measurement technology, 2020,43(13) [7] Chen yan. [8] dai lirong, Chen wanmi, guo sheng. Analysis of face recognition method based on BP neural network [J]. Information and computer (theory edition), 2020,32(23). Research on face recognition based on skin color model and SURF algorithm [J]. Industrial control computer, 2014,27(02)