%Generates a simple, connected, bipartite, 3-regular graph of size 1000, then swaps  EdgeFlipsPerStep 
%edges, calculates and stores second to largest eigenvalue, and repeats.
%Then uses Pearson's formula for Autocorrelation (Aut), and saves data periodically
clear all
close all
%warning off MATLAB:eigs:SigmaChangedToLA
pack
tic
E=0;
k=3;
options.disp=0;
%EdgeFlipsPerStep=1;
flipsVec = [86 123 128 229 229 263 263 706 706 706 706];
%FlipsVec are the first points when Aut for the corresponding N was negative, amended so that it is monotonic, just to be safe
walkSteps=10000;
nVec=[100 125 158 199 251 316 398 501 630 794 1000];%These are the sizes of ONE HALF of the graphs
EigenTwo=zeros(length(nVec), walkSteps);
for c=1:length(nVec)
   n=nVec(c);
   EdgeFlipsPerStep=flipsVec(c);
   A=spalloc(n,n,3*n); 
   while(max(max(A))~=1)%Continues until SIMPLE graphs is foun
      %This loop uses Steven Miller's collapsing vectors method to generate
      %k-regular graphs.  For description see section 2 in N.C. Wormald's Models of Random Regular Graphs
      Pairs=[randperm(n*k); randperm(n*k)+n];
      A=spalloc(2*n,2*n,3*n);  
      for i=1:(n*k)
         m1= mod(Pairs(1,i),n)+1;
         m2= mod(Pairs(2,i),n)+n+1;         
         A(m1,m2) =  A(m1,m2) + 1;
         A(m2,m1) =  A(m2,m1) + 1;
      end
   end
   Edges=A(1:n, n+1:2*n);
   for w = 1:walkSteps
      EdgesOld = Edges;        
      for x=1:EdgeFlipsPerStep
         [i,j] = find(Edges);
         r1 = ceil(length(i)*rand);
         r2 = ceil(length(j)*rand);
         E1i = i(r1); E1j = j(r1);
         E2i = i(r2); E2j = j(r2);         
         while( Edges(E2i, E1j)==1 | Edges(E1i, E2j)==1)%Keeps going until 2 edges that satisfy Richter's swapping conditions are found
            r1 = ceil(length(i)*rand);
            r2 = ceil(length(j)*rand);
            E1i = i(r1); E1j = j(r1);
            E2i = i(r2); E2j = j(r2);         
         end
         Edges(E1i, E1j)=0; Edges(E2i, E2j)=0;
         Edges(E1i, E2j)=1; Edges(E2i, E1j)=1;
      end
      A=[spalloc(n,n,3*n) Edges; Edges' spalloc(n,n,3*n)];   
      E=sort(eigs(A,2,'LA', options));%Sorted Eigenvalues of A (This line takes bulk of running-time)
      ZeroIfConnected =E(1)==E(2);   
      if(ZeroIfConnected==0)
         EigenTwo(c,w)=E(1);
      else
         Edges=EdgesOld;
         w=w-1;
      end   
      if(mod(w,100)==0)
         save unrelatedCollect1 EigenTwo walkSteps n A 
      end
   end
end
RunTime=toc;
save unrelatedCollect1 EigenTwo walkSteps nVec flipsVec RunTime A