% Created 2013-May-16
% written by Fu Lin
% A C-shaped network example for noise-free leader selection problem.

n = 200;
Length = 1;
load position_cshape

% % Otherwise generate random nodes in a C-shaped region
% ind = 1;
% while 1
%     pos_temp = Length*rand(1,2);
%     if pos_temp(1) <= Length/5 || pos_temp(2) >= Length*(4/5) || pos_temp(2) <= Length*(1/5)
%         position(ind,:) = pos_temp; %#ok<SAGROW>
%         ind = ind + 1;
%     end
%     if ind == n+1
%         break;
%     end
% end

% radius that determines the neighbors of nodes
r = Length/10;

% draw neighbors and compute the incidence matrix of neighboring nodes
[Eg,idx] = neighbors(n,position,r);

% form the graph Laplacian
L = Eg*Eg';

% kappa is taken as the diagonal of L
kappa = diag(L);

%% Start solving the leader selection problem

kval = 1:1:10;

% pre-allocate memory for data collection
Jlow = zeros(size(kval));
Jup = zeros(size(kval));
LSgreed = zeros(n,length(kval));

for i = 1:length(kval)
    
    Nl = kval(i);
    flag = 2; % for the noise-free leader selection formulation  
    [Jlow(i),Jup(i),LSgreed(:,i)] = leaders(L,Nl,kappa,flag);
    
end

%% Plot lower and upper bounds
figure,plot(kval,Jlow,'o-','MarkerSize',12,'LineWidth',2)
hold on
plot(kval,Jup,'ro-','MarkerSize',12,'LineWidth',2)

% plot the gap between lower and upper bounds
figure,plot(kval,Jup-Jlow,'dk-','MarkerSize',12,'LineWidth',2)

%plot the selection of leaders
no_leader = [3 6 9];
for i = 1:length(no_leader)    
    leader_idx = find(LSgreed(:,no_leader(i)));
    pos_leaders = position(leader_idx,:);
    drawleaders(position,idx,pos_leaders);
end
