% Time base synchronization

%% Initialization
clear all;
nodes = 60; %number of nodes of graph
iterations = 800; %number of iterations of the algorithm
G=graph(bucky);
L=full(laplacian(G)); %Laplacian using Matlab function
degreeMax= max(max(L)); %find the greatest degree of graph
alpha=1/degreeMax; %choose parameter to Define Perron matrix
P=eye(nodes)- alpha* L; %create Perron matrix
commonTimeBase=1000; % some big number used to initialize time base
% e.g. in gps time signal used number of weeks and days since January 1980

for i = 1:nodes %initialize the vertices time base + some random offset
time_running(1,i)=commonTimeBase+1000*rand; %init of time base + offset
end
for i = 1:iterations
    %averaging consensus iterations 
    time_running(1+i,:)=P*time_running(i,:)'; 
    %each vertex adds to the computed value some addition, representing...
    %...ticks of its internal oscilator
    time_running(1+i,:)= time_running(1+i,:)+1+2*rand;
    % between 300th and 350th we simulate an outage of 10 sensors
    if (i>300)&(i<500)
    time_running(1+i,10:20)= time_running(200,20:30)   ;
    end
end

%% plot results
figure;
plot(0:iterations, time_running(:,:));
ttl1=title( 'Online time synchronization - with simulated outage  and recovery of 10 nodes'  )
ttl1=set(ttl1,'Interpreter','latex','FontSize', 15);
xlbl1=xlabel('Iterations [-]');
xlbl1=set(xlbl1,'Interpreter','latex');
ylbl1=ylabel('Time in the node [e.g. seconds or ticks]');
ylbl1=set(ylbl1,'Interpreter','latex');
grid;
% 
figure;
h = plot(G);
c = h.EdgeColor;
h.EdgeColor = 'k';
h.LineWidth=1
h.MarkerSize=8;
h.EdgeAlpha=1;
labelnode(h,1:nodes,' ')
