%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CA in 1-dimensional space with periodic boundaries  %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all;

% Number of cells
N=100;

% Number of iterations and output matrix
MAXT=100;
PLOTMAT=zeros(MAXT+1,N);

% Number of states
S=2;

% Number of neighbors (excluding agent)
% NB: Must be even
K=2;

% Defining Radius of Interaction
INTRAD=K/2;

% State space
SP=0:S-1;

% Define rule
RNUM=33;

% Convert rule into output vector
% NB: Second parameter = number of bits required to define a lookup table
% It is equal to the number of possible configurations 
NCONF=S^(K+1);
TEMPOUT=str2num(transpose(dec2bin(RNUM,NCONF)));
OUT=TEMPOUT(NCONF:-1:1);                                    % Neded to correctly match input to outputs                     

% Define neighboring structure
NEIGH=zeros(N,K+1);             % Rows: Cells; Columns: Labels of K+1 Neighbors
LABELS=[[1:N] [1:N] [1:N]];     % Needed in order to allow for boundary conditions

for i=1:N
    h=1;
    for j=-INTRAD:INTRAD
            NEIGH(i,h)=LABELS(N+j+i);
            h=h+1;
    end
end

% Define initial configuration

% Random
%INICONF=unidrnd(2,1,N)-1;

% ONLY MID CELL ON
INICONF=zeros(1,N);
INICONF(N/2)=1;

% Set interation 
time=1;

% Set current configuration (the one agents look to adjust)
CURRCONF=INICONF;
PLOTMAT(1,:)=CURRCONF;

% Begin iteration cycle

while(time<=MAXT)
    time
    TEMPCONF=zeros(1,N);                                % Create temp configuration 
    for i=1:N
        NEIGH_STATUS=CURRCONF(NEIGH(i,:));              % Copy status of neighborhood 
        CELL_INP=bin2dec(num2str(NEIGH_STATUS))+1;      % Compute decimal value of neighborhood 
        CELL_OUT=OUT(CELL_INP);                         % Lookup output value in out matrix
        TEMPCONF(i)=CELL_OUT;
    end
    CURRCONF=TEMPCONF;
    PLOTMAT(time+1,:)=CURRCONF;
    time=time+1;
end

imagesc(PLOTMAT,[0 1])
tit=strcat('Rule = ',num2str(RNUM));
title(tit);
xlabel('Cells');
ylabel('Generations');
colormap(1-gray)

