% EEG Graph analysis
% created the 16/04/2014 by Fabrizio De Vico Fallani for the Ghent Training School

% Load data

load('StrokeEEGcoherence-ah.mat');

load('StrokeEEGcoherence-uh.mat');

load('EEGcoordinates.mat');

% extracting matrices unaffected hand (uh) and affected hand (ah) for theta
% band
theta_uh = squeeze(uh(:,:,1));
theta_ah = squeeze(ah(:,:,1));

figure
subplot(1,2,1)
imagesc(theta_uh)
colorbar
axis square
title('theta band UH')
xlabel('Electrodes')
ylabel('Electrodes')
caxis([0 0.5])

subplot(1,2,2)
imagesc(theta_ah)
colorbar
axis square
title('theta band AH')
xlabel('Electrodes')
ylabel('Electrodes')
caxis([0 0.5])

% Threshold the network
theta_uh_trh = threshold_proportional(theta_uh, 0.25);
theta_ah_trh =threshold_proportional(theta_ah, 0.25);

figure
subplot(1,2,1)
imagesc(theta_uh_trh)
colorbar
axis square
title('theta band UH')
xlabel('Electrodes')
ylabel('Electrodes')
caxis([0 0.5])

subplot(1,2,2)
imagesc(theta_ah_trh)
colorbar
axis square
title('theta band AH')
xlabel('Electrodes')
ylabel('Electrodes')
caxis([0 0.5])

theta_uh_trh_bin = double(logical(theta_uh_trh));
theta_ah_trh_bin = double(logical(theta_ah_trh));

figure
subplot(1,2,1)
imagesc(theta_uh_trh_bin)
colorbar
axis square
title('theta band UH')
xlabel('Electrodes')
ylabel('Electrodes')
caxis([0 0.5])

subplot(1,2,2)
imagesc(theta_ah_trh_bin)
colorbar
axis square
title('theta band AH')
xlabel('Electrodes')
ylabel('Electrodes')
caxis([0 0.5])

% plot networks
[xp yp] = adjacency_plot_und(theta_uh_trh_bin,[x' y']);
figure
plot(xp,yp);

for i = 1:size(theta_uh_trh_bin)
    text(x(i),y(i),Label(i))
end

% computing graph matrix

theta_uh_dens = density_und(theta_uh_trh_bin);

% node degrees
theta_uh_deg = degrees_und(theta_uh_trh_bin);
theta_ah_deg = degrees_und(theta_ah_trh_bin);

figure
plot(theta_uh_deg,'-bo');
hold on
plot(theta_ah_deg,'-ro');
set(gca,'xtick',1:61,'xticklabel',Label)


% global efficiency for unaffected and affected hand
Eg_uh = efficiency_bin(theta_uh_trh_bin,0);
Eg_ah = efficiency_bin(theta_ah_trh_bin,0);

% local efficiency for unaffected affected hand
El_uh = efficiency_bin(theta_uh_trh_bin,1);
El_uh = mean(El_uh);

El_ah = efficiency_bin(theta_ah_trh_bin,1);
El_ah = mean(El_ah);

% random network generation
[theta_uh_trh_bin_R] = randmio_und(theta_uh_trh_bin, 100);

% efficiency values for ranom network
Eg_uh_R = efficiency_bin(theta_uh_trh_bin_R,0);
El_uh_R = efficiency_bin(theta_uh_trh_bin_R,1);
El_uh_R = mean(El_uh_R);

% normalizing brain network efficiency by using random net efficiency value
theta_uh_effG_norm = Eg_uh/Eg_uh_R;
theta_uh_effL_norm = El_uh/El_uh_R;