-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTimeResolvedNets.m
More file actions
2647 lines (2113 loc) · 78.1 KB
/
TimeResolvedNets.m
File metadata and controls
2647 lines (2113 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function []=TimeResolvedNets(TR,K,thr,SNC_size,band,varargin)
% Marika Strindberg, Karolinska Institutet 2018-2020.
% marika.strindberg@ki.se, marikastrindberg@gmail.com
% The ouput of this code is described in "Spatio-temporally flexible subnetworks reveal the quasi-cyclic nature of
% integration and segregation in the human brain", Strindberg et al, 2021
% (Row 87-113 and 282-298 are adapted from Cabral et al 2017)
% TR = Timeresolution of aquisition (repetition time)
% K = Expansion in each iteration to find SNCs, default K=10
% thr = is by default 0, if set higher it only searches trough SNCs with qint
% above this thr
% SNC_size = size of final SNC i.e. number of areas
% band = if 1 then bandpass filter will be used, if 0 IMFs will be calculated
% varargin = If predefined seed areas are prefered, add areas as a vector
% Subrutines:
% SNCs.m calculates the subnetworks
% PhaseIntegrationSNC.m calculates the phase coherence within a subset
% of empirically derived SNCs and randomly composed SNCs
% Example use: TimeResolvedNets(0.72,10,0,8,0)
% Not that the directories on lines
% 61,67,1331,1341,1590,1599,1644,1653,2538,2547,2570,2579 needs to be utdated to fit the
% local environement.
% BrainNet viewer needs to be installed for the visualizations of networks,
% see ReadMe for further details.
% Main calculations:
% 1a. In the case of IMFs, Decompose signal into IMFs and decide which IMF to use based on powerspectra
% 1b. In the case of band-pass filter, the user will be prompted to set the
% upper and lower filter thresholds
% 2. Louvain communities are calculuated for all areas for all timepoints and subjects.
% 3. Louvain run is chosen
% 4. Calculation of SNCs
% 5. Grouping of SNCs into SNs
% 6. Calculation of SNC timeseries and SNC phase
% 7. Calculation of SN timeseries and SN phase
% 8. Calculate integration and segregation of SNs relative to a) time of overlap b) all
% time as well as relative activation/deactivation
% 9. Selection of hierachical cluster solution that maximizes integration within MNs
% 10. Meta-network timeseries and maps
% 11. Naming of MNs
% 12. SN maps
% 13. Video of MN and SN maps
% 17. State vector recurrence plots
% 14. Phase coherence within and between SNs in the same community and
% between SNs in different commmunities
% 15. Phase coherence for a sample of SNC an d random components prior to and during integration
% 16. Duration of SNs
% 17. Calculation of number of SNs per timepoint,average number of communities SNs are integrated each timepoint, number of areas per SN
% 18. Calculation relative flexibility/modularity of areas
% %
% Set the directory where the BOLD timeseries of all subjects are located
BOLD=dir('/Users/marist1/Documents/TEST/*.txt');
S=length(BOLD);
%Load BOLD signals into matrix BOLDdata
for s=1:S
BOLDdata(s,:,:)=load(['/Users/marist1/Documents/TEST/' BOLD(s).name]);
end
save BOLD BOLDdata
load BOLD
[S N T]= size(BOLDdata)
if band == 1
%%%% 1.Bandpass instead of EMD%%
j=1;
j_common=1;
b1=input("Choose lower threshold for bandpass filter ")
b2=input("Choose upper threshold for bandpass filter ")
[S, N, T]=size(BOLDdata);
% Bandpass filter settings
fnq=1/(2*TR); % Nyquist frequency
flp = b1; % lowpass frequency of filter (Hz)
fhi = b2; % highpass
Wn=[flp/fnq fhi/fnq]; % butterworth bandpass non-dimensional frequency
k=2; % 2nd order butterworth filter
[bfilt,afilt]=butter(k,Wn); % construct the filter
clear fnq flp fhi Wn k
BOLD_band=zeros(S,N,T);
for s=1:S
BOLD = squeeze(BOLDdata(s,:,:));
% Filter signal and then get phase using the Hilbert transform
for n=1:N
BOLD(n,:)=BOLD(n,:)-mean(BOLD(n,:));
BOLD_band(s,n,:)=filtfilt(bfilt,afilt,BOLD(n,:));
end
end
for s=1:S
for n=1:N
Phase_imf(s,n,1,:)=angle(hilbert(BOLD_band(s,n,:)));
end
end
save PhaseAndImf Phase_imf BOLD_band
else
%%%% 1.Decompose all timeseries into imperical mode functions%%.
fs=1/TR;
imf_freq=zeros(S,N,T,10);
BOLD_imf=zeros(S,N,T,10);
for s=1:S
%Decompose signals fo all parcels into imfs
x=squeeze(BOLDdata(s,:,:));
for p=1:N
y=squeeze(x(p,:));
y=y(:)-mean(y(:));
[imf,~]=emd(y);
[hs,~,~,imfinsf,~]=hht(imf,fs); %to get the freq content for power spectrum
[a b]=size(imf);
IMFnr(s,p)=b;
clear hs
imf_freq(s,p,:,1:b)=imfinsf;
BOLD_imf(s,p,:,1:b)=imf;
imf=[];
imfinsf=[];
end
end
%
j_common=min(IMFnr(:))
disp(sprintf('Minimum number of IMFs common to all areas and all participants: %d',j_common ))
for s=1:S
for p=1:N
for i=1:j_common
Phase_imf(s,p,i,:)=angle(hilbert(BOLD_imf(s,p,:,i)));
end
end
end
save PhaseAndImf Phase_imf BOLD_imf imf_freq IMFnr
%Powerspectra for shared IMFs
% Plot Power Spectrum for all nodes&subjects in each IMF
w = T;
Ts = w*TR; % define total duration of sample in seconds
freq = (0:w/2-1)/Ts; % frequency range in Hz
PS=zeros(j_common,numel(freq));
PW=zeros(j_common,numel(freq));
t=0
for imf=1:j_common
for s=1:S
for n=1:N
X=squeeze(BOLD_imf(s,n,:,imf));
pw = abs(fft(X-mean(X)));
ps_X=pw(1:floor(w/2)).^2/(w/2);
PS(imf,:)=PS(imf,:)+ps_X';
PW=PW(imf,:)+pw;
t=t+1;
end
end
end
figure
a=[1:1:j_common]
for i=1:j_common
hold on
plot(freq,PS(i,:),'LineWidth',2)
Psum=sum(PS(i,:));
[r c]=find(PS(i,:)==max(PS(i,:)));
Peak(i)=freq(c)
end
xlabel('Frequency (Hz)')
ylabel('Power')
%%legend('IMF 1','IMF 2','IMF 3','IMF 4','IMF 5','IMF 6')
%Power spectrum for BOLD signal
PSBold=zeros(1,numel(freq));
for s=1:S
for n=1:N
X=squeeze(BOLDdata(s,n,:));
pw = abs(fft(X-mean(X)));
ps_X=pw(1:floor(w/2)).^2/(w/2);
PSBold=PSBold+ps_X';
end
end
hold on
plot(freq,PSBold,'LineWidth',2)
legend
%Range of power spectra for the IMFs: column1=peak, column 2=99% of power
%below this frequency, column 3=99% of power above this frequency
for i=1:j_common
[r c]=find(PS(i,:)==max(PS(i,:)))
PsN(i,1)=freq(c)
a=sum(PS(i,:))
for j=1:T/2
a2=sum(PS(i,1:j));
if a2>=a*0.99 %approx max freq
PsN(i,2)=freq(j)
break
end
end
end
for i=1:j_common
a=sum(PS(i,:));
for j=1:Ts
a2=sum(PS(i,1:j));
if a2>=a*0.01 %approx min freq
PsN(i,3)=freq(j)
break
end
end
end
%How much of the power <0.1 Hz is contained in each IMF
% Find threshold 0.1Hz
F=freq
f=F(freq<=0.1);
for i=1:j_common
powerBOLDclassic(i)=sum(sum(PS(i,1:numel(f))))/sum(sum(PS(:,1:numel(f))))
end
format short g
fileID = fopen('IMFsummary.txt','w')
fprintf(fileID,'Min number of common IMFs %d \n',j_common)
for i=1:j_common
a1=powerBOLDclassic(i)
a2=PsN(i,1)
a3=PsN(i,3)
a4=PsN(i,2)
fprintf(fileID,'IMF %d \n', i)
fprintf(fileID,'Power <=0.1Hz %d \n', a1)
fprintf(fileID,'Peak freq (hz) %d \n', a2 )
fprintf(fileID,'Range (99 percentil of distribution) %d - %d \n',a3, a4)
end
fclose(fileID)
j=input("Choose IMF ")
end
%%%
%for each timepoint compute dPC for the band pass filtered signal or the IMFs(j_common), Louvain communites
%division as well as Leida weights
L=100 %Number of iterations of the Louvain alogrithm
Louvain_s=zeros(L,S,T-10,N);
%Calculate the dPCs
for s=1:S
iFCalls=zeros(T-10,N,N);
parfor t=1:T-10 % Five first and last timepoints are not used due to artefacts resulting from the hilbert transformation
% Calculate phase difference matrixes dFC
dPC=zeros(N,N);
for m=1:N
for n=1:N
if n>m
dPC(m,n)=cos(Phase_imf(s,m,j,t+5)-Phase_imf(s,n,j,t+5));
else
end
end
end
dPC=dPC+tril(dPC',1);
iFCalls(t,:,:)=dPC;
% Calculate the Louvain communities
for k=1:L
CLPs=community_louvain(dPC,1,[],'negative_sym');
Louvain_s(k,s,t,:)=CLPs;
end
end
save(sprintf('iFCall_s%d',s), 'iFCalls', '-v7.3')
end
save(sprintf('Louvain%d_%d',j,K), 'Louvain_s', '-v7.3')
L=100
Tmax=T-10;
PairW=zeros(L,S,N,N);
for k=1:L
for s=1:S
A=squeeze(Louvain_s(k,s,:,:));
for n=1:N
for m=1:N
if m>=n
PairW(k,s,n,m)=numel(nonzeros(A(:,n)==A(:,m)))/Tmax;
PairW(k,s,m,n)=numel(nonzeros(A(:,n)==A(:,m)))/Tmax;
else
end
end
end
end
end
for k=1:L
for n=1:N
for m=1:N
Mean_matrix(k,n,m)=mean(PairW(k,:,n,m));
Min_matrix(k,n,m)=min(PairW(k,:,n,m));
Max_matrix(k,n,m)=max(PairW(k,:,n,m));
Var_matrix(k,n,m)=std(PairW(k,:,n,m));
end
end
end
save(sprintf('PairWise_K%d_%d',K,j), 'Mean_matrix', 'Min_matrix', 'Max_matrix' ,'Var_matrix', '-v7.3')
% Find the most representative Louvain solution ie the one that contains most pairs with highest frequency accross the iterations
QM=zeros(N,N);
OrdAll=[];
for k=1:L
V=squeeze(Mean_matrix(k,:,:));
V=V-diag(diag(V));
V=triu(V);
[row col]=find(V>0);
R=[row col];
R=sort(R,2);
R=unique(R,'rows');
for i=1:length(R)
Qr(i)=V(R(i,1),R(i,2));
end
QR=[R Qr'];
QRs=sortrows(QR,3,'descend');
Ord=[];
for i=1:N
temp=[];r=[];tempmax=[];
[r c]=find(QRs==i);
temp=QRs(r,:);
tempmax=max((QRs(r,3))); % BUGfix added 6 july
[rx ~]=find(temp==tempmax); %
Ord(i)=r(rx(1)); %
end
Ord=unique(Ord); % Remove dublicates
rr=find(Ord>length(R));
if rr>0
for i=1:numel(rr)
r2(i)=Ord(rr(i))-length(R);
end
Ord(rr)=r2;
end
QRtop=QRs(Ord,:);
%test that all areas are included
QRtopS(k,1:length(Ord),:)=sortrows(QRtop,3,'descend');
Q=squeeze(QRtop(:,1:2));
%Count number of top pair frequency
for m=1:length(Ord)
QM(Q(m,1),Q(m,2))=QM(Q(m,1),Q(m,2))+1;
end
OrdAll(k)=numel(Ord); %Bugfix 18 July
end
save QRsTOP_IMFiter QRtopS QM OrdAll
figure; imagesc(QM)
QT=QRtopS(:,:,1:2);
MAX=max(QM(:));
[row col]=find(QM==MAX)
f1=[row col];
Hh=unique(nonzeros(QM)); %Different frequencies
HH=sort(Hh,'descend');
E=length(HH); % Nr of different frequencies
CG=zeros(L,E); % Areas per freq
if numel(HH)>1 % Added to accomodate the possibility that all Louvain solutions create exactly the same TOP pairs
TOP=[];
TOPs=[];
for e=1:E
f=[];
[row col]=find(QM==HH(e)); % Find pairs with freq HH(e)
f=[row col];
fl= numel(row); % number of pairs with freq HH(e)
for i=1:L %count how many of the pairs of frequency HH(e) that are part of each solution i
d=squeeze(QT(i,:,:));
temp=numel(nonzeros(d(:,1))); %nonzero rows
noninc=length(unique([f;d(1:temp,:)],'rows'))-temp; % pairs from solution i that are not part of accumulated pairs with not part solution
CG(i,e)=(fl-noninc)/temp; % accumulated percentage of of pairs
end
TEMPsum=sum(CG,2);
[rr cc]=find(TEMPsum>0.999); % see if some solution has all pairs included
if length(rr>0)
final=e;
rof=rr(1)
break
end
end
else % if all Louvain solutions give exactly the same TOP pairs
rof=1
end
TOP=squeeze(QT(rof,1:OrdAll(rof),:)); % Bugfix 18 July
TOPS=squeeze(QRtopS(rof,1:OrdAll(rof),:)); %Bugfix 18 July
if S>1
Louv=squeeze(Louvain_s(rof,:,:,:));
else
Louv(1,:,:)=squeeze(Louvain_s(rof,:,:,:));
end
V=squeeze(Mean_matrix(rof,:,:));
C=mean(mean(V))*diag(diag(V));
V=V-diag(diag(V));
V1=V+C;
figure; imagesc(V1)
colorbar
colormap('jet')
title(['Qint Matrix ',num2str(k),' mean ', num2str(round(mean(mean(V1)),3)),', max ',num2str(round(max(max(V1)),3)),', min ',num2str(round(min(min(V1)),3)) ])
Image = getframe(gcf);
imwrite(Image.cdata, sprintf('PairWiseQint.jpg'));
if size(varargin)>0
TOP=cell2mat(varargin);
tempo=size(TOP);
if tempo(1,1)==1% Make inte vertical vector if horizontal
TOP=TOP';
end
save(sprintf('Top'), 'TOP','Louv','CG','V','r','-v7.3')
else
save(sprintf('Top'), 'TOP', 'TOPS','Louv','CG','V','r','-v7.3')
end
%%%%%% Get subnetworks (SNCs and SNs) %%%%%
%Decide if seed is even or odd
xc=size(TOP)
if min(xc)==1
evenodd=1
else
evenodd=0
end
%%%%%%%%
if evenodd==0
%Choose If PDFs should be calculated
aa=input('Do you want to background probability distributions? if yes type 1 if NO type 0')
if aa==1
X=input('How many random samples?')
%Create probability distributions:
load Top
pp=[4 6 8 10 12]
for nn=1:numel(pp)
nn
a=0;
n=pp(nn)
randComp=zeros(X,n);
Qint=zeros(X,S);
MeanInt=[];
p=0;
for r=1:X
r
ran = round(1 + (N-1).*rand(n,1),0);
if numel(unique(ran))==n % ~(randomA(1,1)==randomA(2,1))
p=p+1
randComp(p,:)=ran;
if S>1
parfor s=1:S
tempB=squeeze(Louv(s,:,:));% Time and community
InCom=0;
y=tempB(:,ran);
z=prod(y,2); %Row with same community nr have product 1^6=1,2^6=64,3^6=729
if n==4
zz=(z==[1 16 81 ]);
elseif n==6
zz=(z==[1 64 729]);
elseif n==8
zz=(z==[1 256 6561]);
elseif n==10
zz=(z==[1 1024 59049]);
else
zz=(z==[1 4096 531441]);
end
zzz=(zz(:,1)+zz(:,2)+zz(:,3));
TimeOfInt(s,p,:)=zzz;
InCom=numel(nonzeros(zzz));
Qint(p,s)=InCom/Tmax;
end
else
for s=1:S
tempB=squeeze(Louv(s,:,:));% Time and community
InCom=0;
y=tempB(:,ran);
z=prod(y,2);
if n==4
zz=(z==[1 16 81 ]);
elseif n==6
zz=(z==[1 64 729]);
elseif n==8
zz=(z==[1 256 6561]);
elseif n==10
zz=(z==[1 1024 59049]);
else
zz=(z==[1 4096 531441]);
end
zzz=(zz(:,1)+zz(:,2)+zz(:,3));
TimeOfInt(s,p,:)=zzz;
InCom=numel(nonzeros(zzz));
Qint(p,s)=InCom/Tmax;
end
end
MeanInt(p)=mean(Qint(p,:));
randComp(p,:)=ran;
end
end
MeanPDF(nn,1)=mean(MeanInt);
MeanPDF(nn,2)=std(MeanInt);
save(sprintf('PDF_IMF_%d',n),'randComp','MeanInt','Qint','MeanPDF','TimeOfInt''-v7.3')
end
figure
p=[4 6 8 10 12];
for i=1:5
load(sprintf('PDF_IMF_%d',p(i)))
ME(i,1)=numel(nonzeros(MeanInt))/numel(MeanInt) %percent non-zero entries
ME(i,2)=mean(MeanInt)
ME(i,3)=std(MeanInt)
ME(i,4)=max(MeanInt)
ME(i,5)=min(MeanInt)
hold on;histogram(MeanInt,50,'Normalization','probability')
end
title('PDFs Random components')
legend('size 4','size 6','size 8','size 10', 'size 12')
xlabel('qint')
ylabel('probability')
else
end
end
%%%%Get SNCs
Tmax=T-10;
%SNC_size=input('Choose size of SNCs (default=8, other options 10 or 12 if initital seed was a pair, otherwise odd numbers up to 11)')
SNCs(K,Louv,V,TOP,Tmax,S,N,SNC_size,thr,evenodd) % calculatest the SNCs
%%%% Get SNs
u=input('Does OV need to be empirically set (ie if parcellation is used that substantially larger or smaller than N=236 and/or SNC_size that is not 8).0=no, 1=yes')
if u==0
ov=5
else
ov=1;
end
for OV=ov:SNC_size
if SNC_size==8||SNC_size==7
load(sprintf('P%d_I8',K))
H=R8_IDXsUfreqSort;
elseif SNC_size==6||SNC_size==5
load(sprintf('P%d_I6',K))
H=R6_IDXsUfreqSort;
elseif SNC_size==4||SNC_size==3
load(sprintf('P%d_I4',K))
H=R4_IDXsUfreqSort;
elseif SNC_size==10||SNC_size==9
load(sprintf('P%d_I10',K))
H=R10_IDXsUfreqSort;
elseif SNC_size==12||SNC_size==11
load(sprintf('P%d_I12',K))
H=R12_IDXsUfreqSort;
end
if evenodd==1
for i=1:length(H)
Temp(i,:)=unique(H(i,:));
end
H=Temp;
else
Temp=H;
end
H=H(:,2:SNC_size+1); %Only the areas
k=0
for p=1:length(Temp(:,1))
A=nonzeros(unique(Temp(1,2:SNC_size+1))); %Areas of first row.
TT=zeros(length(Temp(:,1)),SNC_size);
k=k+1;
for i=1:SNC_size
Ttemp=zeros(length(Temp(:,1)),SNC_size);
Ttemp(Temp(:,2:SNC_size+1)==A(i))=1;
Hv=sum(Ttemp,2); %make into vector
TT(:,i)=Hv; %rows that overlap with A(i)
end
z=sum(TT,2); %Rows with overlap
r=find(z>(OV-1)); % Rows beloing to SN
D(k,1:numel(r),:)=Temp(r,:);
Temp(r,:)=[]; %Delet rows that are assigned to SN
length(Temp(:,1)) %Length of reminder
if length(Temp(:,1))<=1
break
else
end
end
for i=1:length(D(:,1))
bb=squeeze(D(i,:,2:SNC_size+1)); %Bug update, the 1 was missing
tem=unique(nonzeros(bb(:,:)));
SNs(i,1:numel(tem))=tem;% Bug update
Areas_SNs(i)=numel(tem);% Bugupdate
clear tem
end
max(Areas_SNs)
min(Areas_SNs)
%Spatial Overlap between SNs
NK=zeros(length(D(:,1)),length(D(:,1)));
for i=1:length(D(:,1))
for n=1:length(D(:,1))
if n>i
M(i,n)=numel(intersect(nonzeros(SNs(i,:)),nonzeros(SNs(n,:))));
NK(i,n)=2*numel(intersect(nonzeros(SNs(i,:)),nonzeros(SNs(n,:))))/(Areas_SNs(i)+Areas_SNs(n));
end
end
end
figure; imagesc(M)
figure; imagesc(NK)
save(sprintf('Subnetworks_overlap%d',OV), 'SNs', 'Areas_SNs', 'NK', 'D') %
%%%% Get convergence of SNCs between iterations %%%%
load(sprintf('P%d_I4',K))
P(1,1)=mean(FreqIDXsU4)
P(1,2)=iqr(FreqIDXsU4)
P(1,3)=max(FreqIDXsU4)
P(1,4)=min(FreqIDXsU4)
Konvergence(1)=1-length(R4_IDXsU(:,1))/length(R4_IDXsALL(:,1))
if SNC_size >4
load(sprintf('P%d_I6',K))
P(2,1)=mean(FreqIDXsU6)
P(2,2)=iqr(FreqIDXsU6)
P(2,3)=max(FreqIDXsU6)
P(2,4)=min(FreqIDXsU6)
Konvergence(2)=1-length(R6_IDXsU(:,1))/length(R6_IDXsALL(:,1))
if SNC_size>6
load(sprintf('P%d_I8',K))
P(3,1)=mean(FreqIDXsU8)
P(3,2)=iqr(FreqIDXsU8)
P(3,3)=max(FreqIDXsU8)
P(3,4)=min(FreqIDXsU8)
Konvergence(3)=1-length(R8_IDXsU(:,1))/length(R8_IDXsALL(:,1))
end
end
%%%%%%
%1) Calculate SNC-timeseries and phase integration
load Top Louv
load(sprintf('Subnetworks_overlap%d',OV))
load PhaseAndImf
Phase=squeeze(Phase_imf(:,:,j,6:T-5));
Tmax=T-10;
W=length(D(1,1,:))
for w=1:length(D(:,1,1))
Qint_SNC=[];
w
SNCbinTS=[]; SNCcomTS =[]; SNCmeanPhase=[];
L=length(nonzeros(D(w,:,1)))
SNCbinTS=zeros(S,L,Tmax);
SNCcomTS=zeros(S,L,Tmax);
SNCmeanPhase=zeros(S,L,Tmax);
NN=squeeze(D(w,1:L,2:W));
parfor k=1:L
if L>1
snc=NN(k,:); %the SNC areas
else
snc=NN';
end
for s=1:S
tempB=squeeze(Louv(s,:,:));% Time and community
InCom=0;
y=tempB(:,snc);
z=prod(y,2);
if SNC_size==8
zz=(z==[1 256 6561]); %Row with same community nr have product 1^8=1,2^8=256,3^8=6561
elseif SNC_size==7
zz=(z==[1 128 2187]);
elseif SNC_size==6
zz=(z==[1 64 729]);
elseif SNC_size==5
zz=(z==[1 32 243]);
elseif SNC_size==9
zz=(z==[1 512 19683]);
elseif SNC_size==10
zz=(z==[1 1024 59049]);
elseif SNC_size==11
zz=(z==[1 2048 177147]);
elseif SNC_size==12
zz=(z==[1 4096 531441]);
elseif SNC_size==4
zz=(z==[1 16 81]);
elseif SNC_size==3
zz=(z==[1 8 27]);
end
zzz=(zz(:,1)+zz(:,2)+zz(:,3));
SNCbinTS(s,k,:)=zzz; %Binary timeseries
temp3=tempB(:,snc(1)); % get the community nr of the SNC
temp3(~logical(zzz))=0;
SNCcomTS(s,k,:)=temp3;% timeseries with community beloning
temp5=squeeze(Phase(s,:,:));
SNCmeanPhase(s,k,:)=mean(temp5(snc,:),1);% mean Phase value of the SNC at each timepoint
InCom=numel(nonzeros(zzz));
Qint_SNC(k,s)=InCom/Tmax;
end
end
save(sprintf('SNC8_TS_%d',w),'Qint_SNC', 'SNCbinTS','SNCcomTS','SNCmeanPhase','-v7.3')
end
% test=squeeze(SNCbinTS(2,1,:,:));
% figure; plot(test')
% test=squeeze(SNCcomTS(2,1,:,:));
% figure; plot(test')
%%%% Calculate SN-timeseries and SN mean phase %%%%
% Check the proportion of times SNCs in the same SN are split into
% different communities
Y=length(D(:,1,1))
SNcomTS=zeros(Y,S,Tmax);
ww=zeros(Y,S,Tmax);
T2=zeros(Y,S,Tmax);
Bb=zeros(Y,S,3);
SNmeanPhase=zeros(Y,S,Tmax);
for y=1:Y
y
clear Qint_SNC SNCbinTS SNCcomTS SNCmeanPhase
load(sprintf('SNC8_TS_%d',y))
p=0;
pp=0;
for s=1:S
for t=1:Tmax
a=nonzeros(unique(SNCcomTS(s,:,t)));
if a>0 %if any SNC belonging to the SN is integrated
if numel(a)==1 % if all in the same community
p=p+1;
SNcomTS(y,s,t)=a; %community timeseries
SNmeanPhase(y,s,t)=std(nonzeros(SNCmeanPhase(s,:,t)));
elseif numel(a)>1 %if split into more than one community
pp=pp+1;
ww(y,s,t)=1;
Bb(y,s,1:numel(a))=a;
if numel(a)==2
a1=numel((find(SNCcomTS(s,:,t)==a(1))));%nr of instance of com 1
a2=numel((find(SNCcomTS(s,:,t)==a(2))));%nr of instance of com 2
if a1>a2
SNcomTS(y,s,t)=a(1);
r=find(SNCcomTS(s,:,t)==a(1));
T2(y,s,t)=a2/(a1+a2);
SNmeanPhase(y,s,t)=std(nonzeros(SNCmeanPhase(s,r,t)));
else
SNcomTS(y,s,t)=a(2);
r=find(SNCcomTS(s,:,t)==a(2));
T2(y,s,t)=a1/(a1+a2);
SNmeanPhase(y,s,t)=std(nonzeros(SNCmeanPhase(s,r,t)));
end
else
a1=numel((find(SNCcomTS(s,:,t)==a(1))));
a2=numel((find(SNCcomTS(s,:,t)==a(2))));
a3=numel((find(SNCcomTS(s,:,t)==a(3))));
if a1>a2 && a1>a3
SNcomTS(y,s,t)=a(1);
r=find(SNCcomTS(s,:,t)==a(1));
T2(y,s,t)=(a2/(a1+a2)+a3/(a1+a3))/2;
SNmeanPhase(y,s,t)=std(nonzeros(SNCmeanPhase(s,r,t)));
elseif a2>a1 && a2>a3
SNcomTS(y,s,t)=a(2);
r=find(SNCcomTS(s,:,t)==a(2));
T2(y,s,t)=(a1/(a1+a2)+a3/(a3+a2))/2;
SNmeanPhase(y,s,t)=std(nonzeros(SNCmeanPhase(s,r,t)));
else
SNcomTS(y,s,t)=a(3);
r=find(SNCcomTS(s,:,t)==a(3));
T2(y,s,t)=(a2/(a2+a3)+a1/(a3+a1))/2;%Proportion of clusters in the non dominant community
SNmeanPhase(y,s,t)=std(nonzeros(SNCmeanPhase(s,r,t)));
end
end
end
end
end
QintSN(y,s)=numel(find(SNcomTS(y,s,:)>0))/Tmax;
end
MeanQintSN(y,1)=mean(QintSN(y,:));
MeanQintSN(y,2)=std(QintSN(y,:));
CommunitySplit(y)=pp/(p+pp);
end
if max(CommunitySplit)==0
save SN_Time T2 CommunitySplit QintSN MeanQintSN SNmeanPhase SNcomTS ww Bb
break
else
clear T2 CommunitySplit QintSN MeanQintSN SNmeanPhase SNcomTS ww Bb
clear SNs Areas_SNs NK D
delete SNC8_TS*
if u==0
display(sprintf('At least one SN did not complete internal coherence at OV = %d, a search for an optimal OV is initiated ',ov))
end
end
end
% Plot example of all SN_timeseries for subject 1
temp=squeeze(SNcomTS(:,1,:));
figure;
for i=1:Y
plot(temp(i,:)+i)
hold on;
end
%%%Get mean IMF activation
load PhaseAndImf.mat
if band==0
[S N T J]=size(BOLD_imf)
for s=1:S
imf=squeeze(BOLD_imf(s,:,6:T-5,j));
for a=1:N
IMFdm(s,a,:)=imf(a,:)-mean(imf(a,:)); %normalize imf-timeseries
amp(s,a,:)=IMFdm(s,a,:)/max(abs(IMFdm(s,a,:))); %normalize against max amplitude within imf
%amp(s,a,:)=IMFdm(s,a,:); %only demean
end
end
else
[S N T J]=size(BOLD_band)
for s=1:S
imf=squeeze(BOLD_band(s,:,6:T-5));
for a=1:N
IMFdm(s,a,:)=imf(a,:)-mean(imf(a,:)); %normalize imf-timeseries
amp(s,a,:)=IMFdm(s,a,:)/max(abs(IMFdm(s,a,:))); %normalize against max amplitude within imf
%amp(s,a,:)=IMFdm(s,a,:); %only demean
end
end
end
save Activation amp
%%%%Activation/deactivation of each area in SNs as well as full SN %%%%
load(sprintf('SN_Time'))
load(sprintf('Subnetworks_overlap%d',OV))
load Activation
E=Areas_SNs; %Bug update (E)
Y=numel(Areas_SNs(1,:))% Bug update
TimeArea=zeros(Y,S,Tmax,max(E));
TimeAreaProp=zeros(Y,S,Tmax);
mean_amp=zeros(Y,S,Tmax);
W=length(D(1,1,:));
for y=1:Y
clear Qint_SN SNCbinTS SNCcomTS DD F e DomCom
load([sprintf('SNC8_TS_%d',y)])
DD=squeeze(D(y,:,2:W));
l=length(nonzeros(DD(:,1)));
DD=DD(1:l,:);
for s=1:S
F=squeeze(SNCcomTS(s,:,:));
if l==1
F=F';
end