%
% ISMRM 2021 
%
% Static v. Dynamic connectivity: what's the difference?

% This assignment will illustrate basic concepts relating to dynamic
% characterization of functional connectivity. 


% (1) Load ROI time courses (693 timepoints x 268 rois). The TR of
% this dataset is 2.1 sec, and ROIs have been extracted from the atlas of
% Shen et al., 2013.
roi_data = load('roi_data_268.txt');

% (2) "Static" connectivity: calculate and visualize the
% region-to-region correlation matrix, calculated over the entire
% scan:
corrs_static = corr(roi_data);

figure;
imagesc(corrs_static,[-0.8 0.8]);
title('static FC'); xlabel('ROI'); ylabel('ROI');
 
% (3) "Dynamic" connectivity calculate correlation matrices in sliding windows
% across the scan. Use a window size of 28 points (~1 min), with
% 50% overlap between successive windows. Store the results in a 3D
% matlab array, of dimensions (# rois x # rois x # windows) = (268
% x 268 x 48), in this case.

winsize = 28; 
winshift = 14; 
corrs_dyn = [];
s1 = 1; sn = s1+winsize-1; ct = 1;
while sn < size(roi_data,1)
    [s1 sn]
    data_win = roi_data(s1:sn,:); 
    corrs_dyn(:,:,ct) = corr(data_win);
    s1 = s1+winshift;
    sn = s1+winsize-1;
    ct = ct+1;
end

% (4) Visualize your sliding-window correlation matrices as a
% movie. 

figure; 
for kk=1:size(corrs_dyn,3);
    imagesc(corrs_dyn(:,:,kk),[-0.8 0.8]); colorbar;
    title(['window # ',num2str(kk)]); 
    xlabel('ROI'); ylabel('ROI');
    axis square;
    pause; 
end

% Questions for you!
% (5) Report some of your observations. 


% (6) Plot the time course of sliding-window correlation between nodes (ROIs) #107
% and #113. Set the y-axis limits to [-1,1].


% (7) Repeat for ROIs #42 and #188.
% Set the y-axis limits to [-1,1].


% (8) Calculate the variance of the sliding window time courses
% derived in parts (6-7).


% (9) Apply k-means clustering to the series of sliding-window
% matrices. Use k=4 clusters, and use the "kmeans"
% function in matlab (with default options for now).
%
% (hint: to form the input 'X' to k-means,
% vectorize the upper or lower triangle of each
% sliding-window matrix. The vector corresponding to window "t" 
% will form the "t"th row of X.)
%
% For future reference, a helpful toolbox for carrying
% out an analysis of dynamic connectivity states (including methods
% for selecting the number of clusters) is the dFNC toolbox in
% GIFT:
% https://trendscenter.org/trends/software/gift/docs/v4.0b_gica_manual.pdf


% (10) Inspect the centroids (reshaped back into matrices).




















