-
Notifications
You must be signed in to change notification settings - Fork 0
/
restsync_main.m
2488 lines (2020 loc) · 108 KB
/
restsync_main.m
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
%%%%%%%%
% Author: David Gruskin
% Contact: [email protected]
% Last updated:03/2022
% Project: Brain connectivity at rest predicts individual differences in normative activity during movie watching
% Description: This is the main analysis and visualization script for the HCP 7T RSFC-ISC project.
% Dependencies:
% [calc_FD.m, make_friston_regressors.m] from https://github.com/DCAN-Labs/dcan_bold_processing
% [kfold_family.m, computeLambdaMax.m, find_lambda.m] from https://github.com/YaleMRRC/CPM/
% [fd_censoring.m, ridgeCPM_bagging.m, hcp_vis.m] from
% https://github.com/davidgruskin/hcp_rsfc_isc
% [rotate_parcellation.m, perm_sphere_p.m] from https://github.com/frantisekvasa/rotate_parcellation
% [cifti-matlab] from https://github.com/Washington-University/cifti-matlab
%%%%%%%%
%% Define variables
% Set these variables before running through the code. If running from
% scratch, create_filtered_fd_files, run_setup, calc_tsnr, and load_data should be set
% to 1. Otherwise, configure as necessary.
% Set to 1 to calculate FC/ISC/correlation between FC and ISC
run_setup = 1;
% Set to 1 to generate filtered FD traces
create_filtered_fd_files = 0;
% Exclude scans if > this fraction of frames are censored
fd_perc = .5;
% Set some motion censoring values here
fd_threshold = 0.2; % remove all frames with fd greater than this value
num_contiguous = 5; % if a run of uncensored frames is less than this value, censor them
% Set to 1 to calculate tsnr
calc_tsnr = 0;
% Set to 1 to load raw data from csvs
load_data = 1;
% Set to 1 to create scalars for visualization
create_scalars = 1;
% Set to 1 if running permutation tests
do_perm = 1;
% Set to 1 to chop off the test-retest montage
cut_montage = 0;
% Set to 1 if using individual parcellations (Schaefer 400)
use_individual = 1;
% Number of permutations to use for CPM/other analyses
num_perm = 10000;
% Set paths to relevant files
data_dir = '/data/data7/HCP_7T';
proj_dir = '/data/data7/restsync/';
individual_parcs_path = fullfile(proj_dir,'inputs','accessory_files','HCP_1029sub_400Parcels_Kong2022_gMSHBM.mat');
figure_path = fullfile(proj_dir,'outputs','svgs/');
hierarchy_path = '/data/data7/restsync/Sensorimotor_Association_Axis_AverageRanks.csv';
wb_path = '/Applications/workbench/bin_macosx64/wb_command';
gifti_path = '/home/davidgruskin/Downloads/gifti-main';
net_assignments_glasser_path = fullfile(proj_dir,'inputs','accessory_files','netassignments_glasser.mat');
pheno_table_path = fullfile(proj_dir,'inputs','accessory_files','hcp_7t_pheno.csv');
pheno_restricted_table_path = fullfile(proj_dir,'inputs','accessory_files','RESTRICTED_dgruskin_3_8_2019_15_47_21.csv');
if use_individual == 1
% Name of parcellation being used
parc_name = 'schaefer400';
scalar_template = fullfile(proj_dir,'inputs','workbench','100610.dscalar.nii');
pconn_template = fullfile(proj_dir,'inputs','workbench','Schaefer2018_400Parcels_7Networks_order.pconn.nii');
indi_sub_list_path = fullfile(proj_dir,'inputs','accessory_files','HCP_subject_list.txt');
else
parc_name = 'glasser360v';
scalar_template = fullfile(proj_dir,'inputs','workbench','Glasser_360v.pscalar.nii');
pconn_template = fullfile(proj_dir,'inputs','workbench','glasser.pconn.nii');
end
if load_data == 1
tsnr_path = fullfile(proj_dir,'inputs','intermediates','tsnr_scans_atlas.mat');
if use_individual == 1
indi_sub_data_path = fullfile(proj_dir,'inputs','intermediates','sub_data_indi.mat');
end
end
save_stem = fullfile(proj_dir,'outputs','ciftis');
%% Add paths and load setup files
% First, add paths
addpath(gifti_path);
addpath(data_dir)
addpath(proj_dir)
addpath(fullfile(proj_dir,'inputs','scripts','cifti-matlab-master'))
% Flip the Cole/Anticevic network labels to account for R/L swap
load(net_assignments_glasser_path);
netassignments_new(1:180,1) = netassignments(181:360);
netassignments_new(181:360,1) = netassignments(1:180);
% Set up parcellation/RSN variables
num_node = 360;
num_edges = 64620;
network_names = {'Visual1','Visual2','Somatomotor','Cingulo-Opercular','Dorsal-attention','Language','Frontoparietal','Auditory','Default','Posterior-Multimodal','Ventral-Multimodal','Orbito-Affective'};
coleanticevic_rgb_networks = [0, 0, 225;100, 0, 255; 0, 255, 255; 153, 0 ,153; 0, 255, 0; 0, 154, 154; 255, 255, 0; 249, 61, 251; 255, 0, 0; 177, 89, 40; 255, 156, 0; 65, 124, 0];
coleanticevic_rgb_nodes = zeros(num_node,3);
for node = 1:num_node
coleanticevic_rgb_nodes(node,:) = coleanticevic_rgb_networks(netassignments(node,1),:);
end
% Set up files for spin testing
spin_coords = importdata(fullfile(proj_dir,'inputs','spin_dir','sphere_HCP.txt'));
coord_l = spin_coords(1:180,:);
coord_r = spin_coords(181:360,:);
%% Data loading
% Prepare pheno tables
pheno_table = readtable(pheno_table_path);
pheno_restricted = readtable(pheno_restricted_table_path);
pheno_restricted = [pheno_restricted(:,1:5) pheno_restricted(:,6:end) pheno_table(:,2:end)];
IDs = pheno_restricted.Subject;
% Set basic variables
num_subj = 184;
num_scan = 8;
num_net = 12;
num_days = 2;
% These subjects are missing some amount of rest/movie data, so they
% will be excluded from analysis
all_excludes = [8,66,124,126,130,135,179,183];
all_used = 1:num_subj;
all_used(all_excludes) = [];
% These subjects are only missing rest data, may be useful for later
% analyses
all_excludes_movie = [66,124,126,130,135,183];
all_used_movie = 1:num_subj;
all_used_movie(all_excludes_movie) = [];
% Get demographics
age_mean = mean(pheno_restricted.Age_in_Yrs(all_used,1));
age_std = std(pheno_restricted.Age_in_Yrs(all_used,1));
num_female = sum(grp2idx(pheno_table.Gender(all_used,1)) == 2);
race_percentages = countcats(categorical(pheno_restricted.Race(all_used,1)))/length(all_used);
ethnicity_percentages = countcats(categorical(pheno_restricted.Ethnicity(all_used,1)))/length(all_used);
% Set scan names for data loading (REST1-REST2-MOVIE1-MOVIE2)
scan_names = cell(8,1);
scan_names{1} = 'rfMRI_REST1_7T_PA';scan_names{2} = 'rfMRI_REST2_7T_AP';scan_names{3} = 'rfMRI_REST3_7T_PA';scan_names{4} = 'rfMRI_REST4_7T_AP';
scan_names{5} = 'tfMRI_MOVIE1_7T_AP';scan_names{6} = 'tfMRI_MOVIE2_7T_PA';scan_names{7} = 'tfMRI_MOVIE3_7T_PA';scan_names{8} = 'tfMRI_MOVIE4_7T_AP';
scan_lengths = [900,900,900,900,921,918,915,901];
% Set family IDs
family_ids(:,1) = 1:num_subj;
family_ids(:,2) = grp2idx(pheno_restricted.Family_ID);
%% Calculate tSNR for each scan
% Initialize matrices
tsnr_scans = zeros(num_subj,num_scan);
tsnr_scans_cat = zeros(num_subj,num_scan/2);
if calc_tsnr == 1
for scan_id = 4:num_scan
disp(strcat(['Calculating tSNR for scan ', num2str(scan_id)]))
parfor subj = 1:length(IDs)
filename_tsnr = strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/',scan_names{scan_id},sprintf('_Atlas.dtseries.nii'));
if exist(filename_tsnr,'file') == 2
cifti_file = ciftiopen(filename_tsnr,wb_path);
cifti_data = cifti_file.cdata;
tsnr_val = nanmean(nanmean(cifti_data')./std(cifti_data'));
tsnr_scans(subj,scan_id) = tsnr_val;
else
tsnr_scans(subj,scan_id) = NaN;
end
end
end
save(tsnr_path,'tsnr_scans');
else
load(tsnr_path)
end
tsnr_scans_cat(:,1) = nanmean(cat(2,tsnr_scans(:,1),tsnr_scans(:,2)),2);
tsnr_scans_cat(:,2) = nanmean(cat(2,tsnr_scans(:,3),tsnr_scans(:,4)),2);
tsnr_scans_cat(:,3) = (tsnr_scans(:,5)*(scan_lengths(5)/(scan_lengths(5) + scan_lengths(6)))) + (tsnr_scans(:,6)*(scan_lengths(6)/(scan_lengths(5) + scan_lengths(6))));
tsnr_scans_cat(:,4) = (tsnr_scans(:,7)*(scan_lengths(7)/(scan_lengths(7) + scan_lengths(8)))) + (tsnr_scans(:,8)*(scan_lengths(8)/(scan_lengths(7) + scan_lengths(8))));
%% Create filtered fd files (this section adapted from https://github.com/DCAN-Labs/dcan_bold_processing)
if create_filtered_fd_files == 1
head_ratio_cm = 5;
TR = 1;
LP_freq_min = 12;
order = 4;
% filter design
hr_min = LP_freq_min; % recasted to reuse code
hr = hr_min/60;
fs = 1/TR;
fNy = fs/2;
fa = abs(hr - floor((hr + fNy) / fs) * fs);
% cutting frequency normalized between 0 and nyquist
Wn = min(fa)/fNy;
if ~isempty(order)
b_filt = fir1(order, Wn, 'low');
a_filt = 1;
end
num_f_apply = 0;
% Read individual movement regressors files
for subj = 1:num_subj
path_mov_reg = strcat('/data/data7/HCP_7T/',num2str(IDs(subj,1)),'/MNINonLinear/Results');
pathstring = [path_mov_reg filesep '*' filesep 'Movement_Regressors.txt'];
path_contents = dir(pathstring);
n = size(path_contents,1);
for i = 1:n
% Read motion numbers
file_mov_reg = [path_contents(i).folder filesep path_contents(i).name]; %-- for MATLAB USE
MR = dlmread(file_mov_reg);
MR_ld = make_friston_regressors(MR);%% Using this function to only get the linear displacements
MR_ld = MR_ld(:,1:6);
split_name = split(file_mov_reg,'/');
scan_id = split_name{end-1};
%'FiltFilt_all';
MR_filt = filtfilt(b_filt,a_filt,MR_ld);
for i = 1:num_f_apply-1
MR_filt = filtfilt(b_filt,a_filt,MR_filt);
end
hd_mm = 10 * head_ratio_cm; % cm to mm conversion
MR_backed = MR_filt;
MR_backed(:, 4:end) = 180*MR_backed(:,4:end)/(pi*hd_mm);
%% The last 6 movement regressors are derivatives of the first 6. Needed for task fMRI, but not used in the Fair Lab
second_derivs = cat(1, [0 0 0 0 0 0], diff(MR_backed(:,1:6)));
MR_backed = [MR_backed second_derivs];
MR_new = MR_backed(:, [1 2 3 4 5 6]);
MR_new(:,4:end) = MR_new(:,4:end)*pi*50/180; % Calculate length of arc in mm
dX = diff(MR_new); % calculate derivatives
FD = (sum(abs(dX),2)); % calculate FD
filename_out = strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_id,'/FD1.mat');
save(filename_out,'FD')
end
end
%% Get indices of censored volumes
for scan_id = 1:num_scan
for subj = 1:length(IDs)
fd_filename = strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/FD1.mat');
if exist(fd_filename,'file') == 2
FD = load(fd_filename);
vols_to_censor = fd_censoring(FD.FD,fd_threshold,num_contiguous);
if ~isempty(vols_to_censor)
vols_mat = zeros(length(FD.FD)+1,size(vols_to_censor,1));
for row = 1:size(vols_to_censor,1)
vols_mat(vols_to_censor(row,1),row) = 1;
end
if create_filtered_fd_files == 1
writematrix(vols_mat,strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/motion_regressors1.csv'));
clear vols_mat FD
end
end
end
end
end
end
%% GSR/Spike Regression and Parcellation
% After running all of the code up until this point, a file called
% "motion_regressors1.csv" should have been created for all scans in which
% there are frames that exceed the specified FD threshold. To censor these
% frames and remove the global signal (and its derivative) from the data,
% run "restsync_denoise.py" followed by "restsync_parcellate.py," which
% will generate csvs with denoised, parcellated data to be loaded in the
% next section. Instructions for running the python scripts can be found in
% the header of each script.
%% Load imaging data
if load_data == 1
% Initialize matrices
sub_data = cell(num_scan,1); % this variable will contain the parcel-wise raw timecourses
perc_mat = zeros(num_subj,num_scan); % this variable will contain the % of frames censored per individual/scan
mean_FD_uncensored = NaN(num_subj,num_scan); % this variable will contain the mean FD of the uncensored FD trace per individual/scan
mean_FD_unfiltered = NaN(num_subj,num_scan); % ' ' but for the unfiltered FD trace
mean_FD_censored = NaN(num_subj,num_scan); % ' ' but for the censored FD trace
full_fd_mat = cell(num_scan,1);
% load individual parcellations
if use_individual == 1
load(individual_parcs_path)
sub_list = load(indi_sub_list_path);
[sharedvals,idx] = intersect(sub_list,IDs,"stable");
[sharedvals2,idx2] = intersect(IDs,sub_list,"stable");
sub_ids_both = IDs(idx2);
lh_labels_all = lh_labels_all(:,idx);
rh_labels_all = rh_labels_all(:,idx);
all_labels = cat(1,lh_labels_all,rh_labels_all);
no_parc = setdiff(IDs,sub_list);
[~,no_parc_ids] = intersect(IDs,no_parc,"stable");
all_excludes = unique(cat(1,all_excludes,no_parc_ids'));
all_used = setdiff(1:184,all_excludes);
end
if use_individual == 0
for scan_id = 1:num_scan
disp(strcat(['Loading data for scan ', num2str(scan_id)]))
% Regress motion only for rest scans
if scan_id < 5
regress_motion = 1;
exemplar_subdata = csvread(strcat(data_dir,'/','100610','/MNINonLinear/Results/',scan_names{scan_id},'/',scan_names{scan_id},sprintf('_Atlas_hp2000_clean_nilearn_%s.csv',parc_name)));
else
regress_motion = 0;
exemplar_subdata = csvread(strcat(data_dir,'/','100610','/MNINonLinear/Results/',scan_names{scan_id},'/',scan_names{scan_id},sprintf('_Atlas_hp2000_clean_nilearn_%sGSR_only.csv',parc_name)));
end
for subj = 1:length(IDs)
if regress_motion == 1
filename = strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/',scan_names{scan_id},sprintf('_Atlas_hp2000_clean_nilearn_%s.csv',parc_name));
elseif regress_motion == 0
filename = strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/',scan_names{scan_id},sprintf('_Atlas_hp2000_clean_nilearn_%sGSR_only.csv',parc_name));
end
if exist(filename,'file') == 2
csvdata = csvread(filename);
if size(csvdata,2) == size(exemplar_subdata,2)
sub_data{scan_id}(:,:,subj) = csvdata;
FD = load(strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/FD1.mat'));
full_fd_mat{scan_id}(subj,:) = FD.FD;
mean_FD_uncensored(subj,scan_id) = nanmean(FD.FD);
vols_to_censor = fd_censoring(FD.FD,fd_threshold,num_contiguous);
perc_mat(subj,scan_id) = length(vols_to_censor)/(length(FD.FD));
hcp_motion_numbers = calcFD(dlmread(strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/Movement_Regressors_dt.txt')));
mean_FD_unfiltered(subj,scan_id) = mean(hcp_motion_numbers);
if ~isempty(vols_to_censor) && regress_motion == 1
vols_mat = zeros(length(FD.FD)+1,size(vols_to_censor,1));
for row = 1:size(vols_to_censor,1)
vols_mat(vols_to_censor(row,1),row) = 1;
end
sub_data{scan_id}(:,vols_to_censor,subj) = NaN;
FD.FD(vols_to_censor,:) = NaN;
mean_FD_censored(subj,scan_id) = nanmean(FD.FD);
end
else
sub_data{scan_id}(:,:,subj) = NaN;
end
else
sub_data{scan_id}(:,:,subj) = NaN;
end
end
end
end
% Load individual parcellations
if use_individual == 1
for scan_id = 1:num_scan
disp(strcat(['Loading data for scan ', num2str(scan_id)]))
% Regress motion only for rest scans
filename_exemplar = strcat('/data/data7/isc_heritability/indi_parc_outputs/100610_',scan_names{scan_id},'_schaefer_indi.ptseries.nii');
exemplar_data = cifti_read(filename_exemplar,wb_path);
exemplar_data = exemplar_data.cdata;
for subj = 1:length(IDs)
filename_ptseries = strcat('/data/data7/isc_heritability/indi_parc_outputs/',num2str(IDs(subj)),'_',scan_names{scan_id},'_schaefer_indi.ptseries.nii');
if exist(filename_ptseries,'file') == 2
csvdata = cifti_read(filename_ptseries,wb_path);
csvdata = csvdata.cdata;
if size(csvdata,2) == size(exemplar_data,2)
sub_data{scan_id}(:,:,subj) = csvdata;
FD = load(strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/FD1.mat'));
full_fd_mat{scan_id}(subj,:) = FD.FD;
mean_FD_uncensored(subj,scan_id) = nanmean(FD.FD);
vols_to_censor = fd_censoring(FD.FD,fd_threshold,num_contiguous);
perc_mat(subj,scan_id) = length(vols_to_censor)/(length(FD.FD));
hcp_motion_numbers = calcFD(dlmread(strcat(data_dir,'/',num2str(IDs(subj,1)),'/MNINonLinear/Results/',scan_names{scan_id},'/Movement_Regressors_dt.txt')));
mean_FD_unfiltered(subj,scan_id) = mean(hcp_motion_numbers);
if ~isempty(vols_to_censor) && scan_id <5
vols_mat = zeros(length(FD.FD)+1,size(vols_to_censor,1));
for row = 1:size(vols_to_censor,1)
vols_mat(vols_to_censor(row,1),row) = 1;
end
sub_data{scan_id}(:,vols_to_censor,subj) = NaN;
FD.FD(vols_to_censor,:) = NaN;
mean_FD_censored(subj,scan_id) = nanmean(FD.FD);
end
else
sub_data{scan_id}(:,:,subj) = NaN;
end
else
sub_data{scan_id}(:,:,subj) = NaN;
end
end
end
end
%% Clean up movie timecourses
% Each movie clip is preceded by 20 seconds of rest. Here, we remove TRs that
% take place in those 20 seconds as well as in the first 20 seconds of each clip
% to account for potential onset transients.
% Initialize matrices
rest_trs = cell(4,1);
movie_cut = cell(4,1);
movie_mask = cell(4,1);
starts = cell(4,1);
ends = cell(4,1);
% Rest blocks- Run 1
starts{1,1} = [0,264.0833,505.75,713.7917,797.5833,901];
starts{1,1} = floor(starts{1,1} +1);
ends{1,1} = [19.9583,284.0417,525.7083,733.75,817.5417,920.9583];
ends{1,1} = floor(ends{1,1} +1);
for i = 1:length(starts{1,1})
rest_trs{1,1} = [rest_trs{1,1} starts{1,1}(i):ends{1,1}(i)];
end
% Rest blocks- Run 2
starts{2,1} = [0,246.75,525.375,794.625,898];
starts{2,1} = floor(starts{2,1}+1);
ends{2,1} = [19.9583,266.7083,545.3333,814.5417,917.9583];
ends{2,1} = floor(ends{2,1}+1);
for i = 1:length(starts{2,1})
rest_trs{2,1} = [rest_trs{2,1} starts{2,1}(i):ends{2,1}(i)];
end
% Rest blocks- Run 3
starts{3,1} = [0,200.5833,405.125,629.25,791.7917,895];
starts{3,1} = floor(starts{3,1}+1);
ends{3,1} = [19.9583,220.5417,425.0833,649.2083,811.5417,914.9583];
ends{3,1} = floor(ends{3,1}+1);
for i = 1:length(starts{3,1})
rest_trs{3,1} = [rest_trs{3,1} starts{3,1}(i):ends{3,1}(i)];
end
% Rest blocks- Run 4
starts{4,1} = [0,252.3333,502.2083,777.4167,881];
starts{4,1} = floor(starts{4,1}+1);
ends{4,1} = [19.9583,272.2917,522.1667,797.5417,900.9583];
ends{4,1} = floor(ends{4,1}+1);
for i = 1:length(starts{4,1})
rest_trs{4,1} = [rest_trs{4,1} starts{4,1}(i):ends{4,1}(i)];
end
% Movie blocks- Run 1
starts{1,2} = [20,284.0833,525.75,733.7917,817.5833];
ends{1,2} = [264.0417,505.7083,713.75,797.5417,900.9583];
starts{1,2} = ceil(starts{1,2}+1);
ends{1,2} = floor(ends{1,2});
if cut_montage == 1
starts{1,2} = starts{1,2}(:,1:size(starts{1,2},2)-1);
ends{1,2} = ends{1,2}(:,1:size(ends{1,2},2)-1);
end
for i = 1:length(starts{1,2})
movie_cut{1,1} = [movie_cut{1,1} starts{1,2}(i):starts{1,2}(i)+19];
movie_mask{1,1}{i} = [starts{1,2}(i)+20 starts{1,1}(i+1)-1];
end
% Movie blocks- Run 2
starts{2,2} = [20,266.75,545.375,814.5833];
ends{2,2} = [246.7083,525.3333,794.5833,897.9583];
starts{2,2} = ceil(starts{2,2}+1);
ends{2,2} = floor(ends{2,2});
if cut_montage == 1
starts{2,2} = starts{2,2}(:,1:size(starts{2,2},2)-1);
ends{2,2} = ends{2,2}(:,1:size(ends{2,2},2)-1);
end
for i = 1:length(starts{2,2})
movie_cut{2,1} = [movie_cut{2,1} starts{2,2}(i):starts{2,2}(i)+19];
movie_mask{2,1}{i} = [starts{2,2}(i)+20 starts{2,1}(i+1)-1];
end
% Movie blocks- Run 3
starts{3,2} = [20,220.5833,425.125,649.25,811.5833];
ends{3,2} = [200.5417,405.0833,629.2083,791.75,894.9583];
starts{3,2} = ceil(starts{3,2}+1);
ends{3,2} = floor(ends{3,2});
if cut_montage == 1
starts{3,2} = starts{3,2}(:,1:size(starts{3,2},2)-1);
ends{3,2} = ends{3,2}(:,1:size(ends{3,2},2)-1);
end
for i = 1:length(starts{3,2})
movie_cut{3,1} = [movie_cut{3,1} starts{3,2}(i):starts{3,2}(i)+19];
movie_mask{3,1}{i} = [starts{3,2}(i)+20 starts{3,1}(i+1)-1];
end
% Movie blocks- Run 4
starts{4,2} = [20,272.3333,522.2083,797.5833];
ends{4,2} = [252.2917,502.1667,777.375,880.9583];
starts{4,2} = ceil(starts{4,2}+1);
ends{4,2} = floor(ends{4,2});
if cut_montage == 1
starts{4,2} = starts{4,2}(:,1:size(starts{4,2},2)-1);
ends{4,2} = ends{4,2}(:,1:size(ends{4,2},2)-1);
end
for i = 1:length(starts{4,2})
movie_cut{4,1} = [movie_cut{4,1} starts{4,2}(i):starts{4,2}(i)+19];
movie_mask{4,1}{i} = [starts{4,2}(i)+20 starts{4,1}(i+1)-1];
end
% Get indices of all frames that need to be removed
all_cut = cell(4,1);
all_cut{1,1} = unique(cat(2,rest_trs{1,1},movie_cut{1,1}));
all_cut{2,1} = unique(cat(2,rest_trs{2,1},movie_cut{2,1}));
all_cut{3,1} = unique(cat(2,rest_trs{3,1},movie_cut{3,1}));
all_cut{4,1} = unique(cat(2,rest_trs{4,1},movie_cut{4,1}));
% Extract movies by clips (not used here but might be helpful to have)
movie_data = cell(4,1);
for scan_id = 5:8
for clip_id = 1:size(movie_mask{scan_id-4,1},2)
movie_data{scan_id-4,clip_id} = sub_data{scan_id,1}(:,(movie_mask{scan_id-4,1}{clip_id}(1,1):movie_mask{scan_id-4,1}{clip_id}(1,2)),:);
end
end
% Remove rest/onset frames
for scan_id = 1:8
if scan_id < 5
sub_data{scan_id,1}(:,1:10,:) = [];
else
sub_data{scan_id,1}(:,all_cut{scan_id-4,1},:) = [];
end
end
% Get mean FD in concatenated rest and movie scans
full_fd_cat{1,1} = cat(2,full_fd_mat{1},full_fd_mat{2});
full_fd_cat{2,1} = cat(2,full_fd_mat{3},full_fd_mat{4});
full_fd_cat{3,1} = cat(2,full_fd_mat{5},full_fd_mat{6});
full_fd_cat{4,1} = cat(2,full_fd_mat{7},full_fd_mat{8});
mean_FD_uncensored_cat = NaN(num_subj,4);
for scan_id = 1:4
mean_FD_uncensored_cat(:,scan_id) = mean(full_fd_cat{scan_id,1},2);
end
mean_FD_uncensored_cat(all_excludes,:) = NaN;
fd_tsnr_scans_cat = cat(2,mean_FD_uncensored_cat,tsnr_scans_cat);
% Define function for z-scoring with NaNs
zscor_xnan = @(x) bsxfun(@rdivide, bsxfun(@minus, x, mean(x,'omitnan')), std(x, 'omitnan'));
% Z-score all timecourses
for scan_id = 1:8
for subj = 1:length(IDs)
sub_data{scan_id,1}(:,:,subj) = zscor_xnan(squeeze(sub_data{scan_id,1}(:,:,subj))')';
end
end
% Concatenate rest and movie scans from the same day
% Order is: Rest Day 1, Rest Day 2, Movie Day 1, Movie Day 2
sub_data_cat{1,1} = cat(2,sub_data{1},sub_data{2});
sub_data_cat{2,1} = cat(2,sub_data{3},sub_data{4});
sub_data_cat{3,1} = cat(2,sub_data{5},sub_data{6});
sub_data_cat{4,1} = cat(2,sub_data{7},sub_data{8});
% Get percentage of frames censored
perc_mat = zeros(num_subj,4);
for scan_id = 1:4
for subj = 1:num_subj
perc_mat(subj,scan_id) = length(find(isnan(sub_data_cat{scan_id,1}(1,:,subj))))/length(sub_data_cat{scan_id,1});
end
end
%% Remove subjects who have incomplete data
for scan_num = 1:4
sub_data_cat{scan_num,1}(:,:,all_excludes) = NaN;
end
elseif use_individual == 1 && load_data == 0
sub_data = load(indi_sub_data_path);
num_subj_indi = 168;
end
%% Calculate FC
hcp_fc = cell(2,1);
num_node = size(sub_data_cat{1,1},1);
parfor scan_id = 1:2
fc_out = zeros(num_node,num_node,num_subj);
for subj = 1:num_subj
fc_out(:,:,subj) = corr(squeeze(sub_data_cat{scan_id,1}(:,:,subj))',squeeze(sub_data_cat{scan_id,1}(:,:,subj))','rows','complete','type','pearson');
end
hcp_fc{scan_id,1} = fc_out;
end
parfor scan_id = 1:2
for subj = 1:num_subj
for node = 1:num_node
hcp_fc{scan_id,1}(node,node,subj) = NaN;
end
end
end
%% Calculate LOO ISC
hcp_isc = zeros(num_subj,num_node,2);
for scan_id = 1:2
sliced = sub_data_cat{scan_id+2,1};
for subj = 1:num_subj
subj
tmp = sliced;
targ = squeeze(sliced(:,:,subj))';
tmp(:,:,subj) = [];
tmp_mean = nanmean(tmp,3)';
for node = 1:size(sliced,1)
hcp_isc(subj,node,scan_id) = corr(targ(:,node),tmp_mean(:,node),'rows','complete','type','pearson');
end
end
end
% Get mean ISC (gISC) across participants and calculate skewness
mean_isc = conv_z2r(squeeze(nanmean(conv_r2z(hcp_isc),2)));
mean_isc_skew = skewness(mean_isc);
% Get mean ISC across parcels
parcel_mean_isc = conv_z2r(squeeze(nanmean(conv_r2z(hcp_isc))));
% Make scalars
if create_scalars == 1
group_name = 'hcp1';
file_name = strcat(parc_name,'_',group_name,'_parcel_meanISC');
write_vec = parcel_mean_isc(:,1);
hcp_vis(wb_path,save_stem,write_vec,scalar_template,file_name);
group_name = 'hcp2';
file_name = strcat(parc_name,'_',group_name,'_parcel_meanISC');
write_vec = parcel_mean_isc(:,2);
hcp_vis(wb_path,save_stem,write_vec,scalar_template,file_name);
end
%% Calculate relationships between tSNR/FD and gISC
[tsnr_isc_r(1,1),tsnr_isc_p(1,1)] = corr(tsnr_scans_cat(:,3),mean_isc(:,1),'rows','complete','type','spearman');
[tsnr_isc_r(2,1),tsnr_isc_p(2,1)] = corr(tsnr_scans_cat(:,4),mean_isc(:,2),'rows','complete','type','spearman');
[fd_isc_r(1,1),fd_isc_p(1,1)] = corr(mean_FD_uncensored_cat(:,3),mean_isc(:,1),'rows','complete','type','spearman');
[fd_isc_r(2,1),fd_isc_p(2,1)] = corr(mean_FD_uncensored_cat(:,4),mean_isc(:,2),'rows','complete','type','spearman');
%% Calculate relationships between FC and ISC
% Initialize matrices
X = zeros(num_node);
edges = (num_node*(num_node-1))/2;
reshaped = zeros(edges, num_subj);
output_matrix_r = zeros(num_node,edges,2);
output_matrix_p = zeros(num_node,edges,2);
square_matrix_r = NaN(num_node,num_node,num_node,4);
% Get square indices
[i,j] = find(tril(ones(num_node), -1));
counter = 1;
for isc_scan = 1:2
for fc_scan = 1:2
% Reshape square matrix to 1D vector
reshaped = zeros(edges, num_subj);
for subj = 1:num_subj
X = squeeze(hcp_fc{fc_scan,1}(:,:,subj));
reshaped(:,subj) = X(logical(tril(ones(size(X)),-1)));
end
% Calculate correlation between RSFC and ISC across participants
fd_cov = cat(2,mean_FD_uncensored_cat(:,[fc_scan,isc_scan+2]),tsnr_scans_cat(:,[fc_scan,isc_scan+2]));
parfor node = 1:num_node
[output_matrix_r(node,:,fc_scan),output_matrix_p(node,:,fc_scan)] = partialcorr(squeeze(hcp_isc(:,node,isc_scan)),reshaped',fd_cov,'rows','complete','type','spearman') ;
end
% Reshape 1D vector to square matrix
for node = 1:num_node
for index = 1:length(i)
square_matrix_r(node,i(index),j(index),counter) = output_matrix_r(node,index,fc_scan);
square_matrix_r(node,j(index),i(index),counter) = output_matrix_r(node,index,fc_scan);
end
end
counter = counter + 1;
end
end
clear counter
%% Get gISC test-retest reliability
% How consistent are ISC maps across both days?
parcel_mean_trt = corr(parcel_mean_isc,'type','spearman');
if do_perm == 1 && use_individual == 0
perm_id = rotate_parcellation(coord_l,coord_r,num_perm);
parcel_mean_trt_p = perm_sphere_p(parcel_mean_isc(:,1),parcel_mean_isc(:,2),perm_id,'spearman');
end
% Residualize ranks with motion (FD) traces
mdl1_gisc_trt = fitlm(cat(2,tiedrank(mean_FD_uncensored_cat(:,3)),tiedrank(mean_FD_uncensored_cat(:,4)),tiedrank(tsnr_scans_cat(:,3)),tiedrank(tsnr_scans_cat(:,4))),tiedrank(mean_isc(:,1)));
mdl2_gisc_trt = fitlm(cat(2,tiedrank(mean_FD_uncensored_cat(:,3)),tiedrank(mean_FD_uncensored_cat(:,4)),tiedrank(tsnr_scans_cat(:,3)),tiedrank(tsnr_scans_cat(:,4))),tiedrank(mean_isc(:,2)));
[r_gisc_trt,p_gisc_trt] = partialcorr(mean_isc(:,1),mean_isc(:,2),cat(2,mean_FD_uncensored_cat(:,3:4),tsnr_scans_cat(:,3:4)),'rows','complete','type','spearman');
% Create scatter of day1/day2 gISC
figure('DefaultAxesFontSize',16)
scatter(mdl1_gisc_trt.Residuals.Raw,mdl2_gisc_trt.Residuals.Raw,'filled'); lsline
xlim([-100 100]); ylim([-100 100])
title('ISC Test-Retest Reliability')
xlabel('Day 1 gISC'); ylabel('Day 2 gISC')
set(gca,{'DefaultAxesXColor','DefaultAxesYColor','DefaultAxesZColor'},{'k','k','k'},'TickDir','out', 'DefaultTextInterpreter', 'none','linewidth',1, 'FontName', 'Arial','box','off')
rtxt = sprintf('Spearman Rho = %s \np-value= %s',num2str(r_gisc_trt), num2str(p_gisc_trt));
t1 = TextLocation(rtxt,'Location','Best'); t1.FontSize = 14;
saveas(gcf,strcat(figure_path,parc_name,'_fig2b_scatter.svg'));
close all
% Create scatter of day1/day2 gISC
figure('DefaultAxesFontSize',16)
scatter(mdl1_gisc_trt.Residuals.Raw,mdl2_gisc_trt.Residuals.Raw,'filled'); lsline
xlim([-100 100]); ylim([-100 100])
title('ISC Test-Retest Reliability')
xlabel('Day 1 gISC'); ylabel('Day 2 gISC')
set(gca,{'DefaultAxesXColor','DefaultAxesYColor','DefaultAxesZColor'},{'k','k','k'},'TickDir','out', 'DefaultTextInterpreter', 'none','linewidth',1, 'FontName', 'Arial','box','off')
rtxt = sprintf('Spearman Rho = %s \np-value= %s',num2str(r_gisc_trt), num2str(p_gisc_trt));
t1 = TextLocation(rtxt,'Location','Best'); t1.FontSize = 14;
saveas(gcf,strcat(figure_path,parc_name,'_fig2b_scatter.svg'));
close all
% Is gISC correlated with tSNR?
[tsnr_gisc_corr_r(1,1),tsnr_gisc_corr_p(1,1)] = corr(mean_isc(:,1),tsnr_scans_cat(:,3),'rows','complete','type','Spearman');
[tsnr_gisc_corr_r(2,1),tsnr_gisc_corr_p(2,1)] = corr(mean_isc(:,2),tsnr_scans_cat(:,4),'rows','complete','type','Spearman');
[tsnr_gisc_pcorr_r(1,1),tsnr_gisc_pcorr_p(1,1)] = partialcorr(mean_isc(:,1),tsnr_scans_cat(:,3),mean_FD_uncensored_cat(:,3),'rows','complete','type','Spearman');
[tsnr_gisc_pcorr_r(2,1),tsnr_gisc_pcorr_p(2,1)] = partialcorr(mean_isc(:,2),tsnr_scans_cat(:,4),mean_FD_uncensored_cat(:,4),'rows','complete','type','spearman');
% How consistent are responses to the TRT clip?
isc_clip_trt = zeros(num_subj,num_subj,2);
for subj1 = 1:num_subj
for subj2 = 1:num_subj
isc_clip_trt(subj1,subj2,1) = conv_z2r(nanmean(conv_r2z(diag(corr(squeeze(movie_data{1,5}(:,:,subj1)),squeeze(movie_data{2,4}(:,:,subj2)))))));
isc_clip_trt(subj1,subj2,2) = conv_z2r(nanmean(conv_r2z(diag(corr(squeeze(movie_data{3,5}(:,:,subj1)),squeeze(movie_data{4,4}(:,:,subj2)))))));
end
end
isc_clip_trt_sub(:,1) = diag(isc_clip_trt(:,:,1));
isc_clip_trt_sub(:,2) = diag(isc_clip_trt(:,:,2));
% Create scatter of day1/day2 gISC (raw, controlling for intrasubject correlation)
mdl1_gisc_trt_intra = fitlm(cat(2,tiedrank(mean_FD_uncensored_cat(:,3)),tiedrank(mean_FD_uncensored_cat(:,4)),tiedrank(tsnr_scans_cat(:,3)),tiedrank(tsnr_scans_cat(:,4)),tiedrank(isc_clip_trt_sub(:,1)),tiedrank(isc_clip_trt_sub(:,2))),tiedrank(mean_isc(:,1)));
mdl2_gisc_trt_intra = fitlm(cat(2,tiedrank(mean_FD_uncensored_cat(:,3)),tiedrank(mean_FD_uncensored_cat(:,4)),tiedrank(tsnr_scans_cat(:,3)),tiedrank(tsnr_scans_cat(:,4)),tiedrank(isc_clip_trt_sub(:,1)),tiedrank(isc_clip_trt_sub(:,2))),tiedrank(mean_isc(:,2)));
[r_gisc_trt_intra,p_gisc_trt_intra] = partialcorr(mean_isc(:,1),mean_isc(:,2),cat(2,mean_FD_uncensored_cat(:,3:4),tsnr_scans_cat(:,3:4),isc_clip_trt_sub),'rows','complete','type','spearman');
figure('DefaultAxesFontSize',16)
scatter(mdl1_gisc_trt_intra.Residuals.Raw,mdl2_gisc_trt_intra.Residuals.Raw,'filled'); lsline
title('ISC Test-Retest Reliability')
xlabel('Day 1 gISC'); ylabel('Day 2 gISC')
set(gca,{'DefaultAxesXColor','DefaultAxesYColor','DefaultAxesZColor'},{'k','k','k'},'TickDir','out', 'DefaultTextInterpreter', 'none','linewidth',1, 'FontName', 'Arial','box','off')
rtxt = sprintf('Spearman Rho = %s \np-value= %s',num2str(r_gisc_trt_intra), num2str(p_gisc_trt_intra));
t1 = TextLocation(rtxt,'Location','Best'); t1.FontSize = 14;
saveas(gcf,strcat(figure_path,parc_name,'_figS3aa_scatter.svg'));
close all
%% Ridge CPM
% First, run 100 iterations of 10-fold CV to train model on Day 1 data and
% test using day 2 data. This will take a while to run (~hours).
[mdl_bagged, ridgeCPMoutput] = ridge_CPM_bagging(hcp_fc, hcp_isc, all_used, sub_data_cat, fd_tsnr_scans_cat, family_ids, 100, 0,zeros(size(all_used,2),num_perm));
% Do rCPM again, this time controlling for intrasubject correlation
fd_tsnr_trt_cat = cat(2,fd_tsnr_scans_cat(:,1:8),isc_clip_trt_sub);
[mdl_bagged_intra, ridgeCPMoutput_intra] = ridge_CPM_bagging(hcp_fc, hcp_isc, all_used, sub_data_cat, fd_tsnr_trt_cat, family_ids, 100, 0,zeros(size(all_used,2),num_perm));
% Next, run 10,000 iterations of the same model with shuffled mean ISC
% scores to generate null distribution for CV comparison. This will take a
% while to run (~days).
if do_perm == 1
s = RandStream('mlfg6331_64','Seed',1);
options = statset('UseParallel',true, ...
'Streams',s,'UseSubstreams',true);
perm_sub_order = zeros(size(all_used,2),num_perm);
for iter = 1:num_perm
perm_sub_order(:,iter) = randperm(s,size(all_used,2));
end
[~, ridgeCPMoutput_perm] = ridge_CPM_bagging(hcp_fc, hcp_isc, all_used, sub_data_cat, fd_tsnr_scans_cat, family_ids, 10000, 1,perm_sub_order);
perm_p = (length(find(ridgeCPMoutput_perm.spearman_out > median(ridgeCPMoutput.spearman_out)))+1)/(num_perm+1);
end
% Run CPM independently for low and high-motion subjects (median split)
motion_med = nanmedian(nanmean(mean_FD_uncensored_cat,2));
sub_ids_low_motion = find(nanmean(mean_FD_uncensored_cat,2)<motion_med);
sub_ids_high_motion = find(nanmean(mean_FD_uncensored_cat,2)>motion_med);
[mdl_bagged_low_motion, ridgeCPMoutput_low_motion] = ridge_CPM_bagging(hcp_fc, hcp_isc, sub_ids_low_motion, sub_data_cat, fd_tsnr_trt_cat, family_ids, 100, 0,zeros(size(all_used,2),num_perm));
[mdl_bagged_high_motion, ridgeCPMoutput_high_motion] = ridge_CPM_bagging(hcp_fc, hcp_isc, sub_ids_high_motion, sub_data_cat, fd_tsnr_trt_cat, family_ids, 100, 0,zeros(size(all_used,2),num_perm));
%% Ridge CPM visualizations
% Get order of parcels by RSN
counter = 1;
indices_reshape = zeros(num_node,1);
for net = 1:num_net
indices = find(netassignments_new(:,1)==net);
indices_reshape((counter:counter+length(indices)-1),1) = indices;
counter = counter + length(indices);
end
clear counter
% Find average ridge coefficient for each FC edge
all_betas = zeros(num_edges,1);
for x = 1:length(mdl_bagged.edge_idx)
all_betas(mdl_bagged.edge_idx(x),1) = mdl_bagged.betas(x,1);
end
% Reshape average ridge coefficients to square
square_matrix_cpm = zeros(num_node,num_node);
[i,j] = find(tril(ones(num_node), -1));
for index = 1:length(i)
square_matrix_cpm(i(index),j(index)) = all_betas(index);
square_matrix_cpm(j(index),i(index)) = all_betas(index);
end
% Separate parcel IDs by RSN affiliation
net_edges = cell(num_net,1);
for net = 1:num_net
net_edges{net,1} = find(netassignments_new(:,1) == net);
end
% Get within network edge IDs
net_coords = cell(num_net,1);
for net = 1:num_net
net_coords{net,1} = combnk(net_edges{net,1},2);
end
% Get between network edge IDs
net_coords_between = cell(num_net,num_net);
for net1 = 1:num_net
for net2 = 1:num_net
row_counter = 1;
for row1 = 1:(size(net_edges{net1,1},1))
for row2 = 1:(size(net_edges{net2,1},1))
net_coords_between{net1,net2}(row_counter,1) = net_edges{net1,1}(row1,1);
net_coords_between{net1,net2}(row_counter,2) = net_edges{net2,1}(row2,1);
row_counter = row_counter +1;
end
end
end
end
clear row_counter
% Combine within + between network edge IDs
net_coords_all = net_coords_between;
for net = 1:num_net
net_coords_all{net,net} = net_coords{net,1};
end
% Create heatmaps to show ridge coefficient represenation by RSN
cont_pos = zeros(num_node);
cont_neg = zeros(num_node);
for node1 = 1:num_node
for node2 = 1:num_node
if square_matrix_cpm(node1,node2)>0
cont_pos(node1,node2) = square_matrix_cpm(node1,node2);
elseif square_matrix_cpm(node1,node2)<0
cont_neg(node1,node2) = square_matrix_cpm(node1,node2);
else
end
end
end
% Negative coefficients
neg_net_out = zeros(num_net,num_net);
for net1 = 1:num_net
for net2 = 1:num_net
if neg_net_out(net1,net2) ~=0
neg_net_out(net2,net1) = 0;
else
tmp = 0;
counter = 0;
for row = 1:size(net_coords_all{net1,net2},1)
tmp = tmp + cont_neg(net_coords_all{net1,net2}(row,1),net_coords_all{net1,net2}(row,2));
if cont_neg(net_coords_all{net1,net2}(row,1),net_coords_all{net1,net2}(row,2)) ~=0
counter = counter + 1;
end
end
neg_net_out(net2,net1) = tmp/counter;
end
end
end
clear counter
neg_net_out(isnan(neg_net_out)) = 0; neg_net_out(isinf(neg_net_out)) = 0;
neg_net_out(:,13) = 0;
neg_net_out(13,:) = 0;
figure
ax(1) = gca;
pcolor(neg_net_out); pbaspect([1 1 1])
caxis([min(min(neg_net_out)),0]); colormin = [50 50 200]; colormax = [255 255 255]; colorneutral = [152 152 227];
n = 1000;
Rlow = linspace(colormin(1)/255,colorneutral(1)/255,n); Rhigh = linspace(colorneutral(1)/255,colormax(1)/255,n);
Blow = linspace(colormin(3)/255,colorneutral(3)/255,n); Bhigh = linspace(colorneutral(3)/255,colormax(3)/255,n);
Glow = linspace(colormin(2)/255,colorneutral(2)/255,n); Ghigh = linspace(colorneutral(2)/255,colormax(2)/255,n);
colormap(ax(1), [cat(1,Rlow(:),Rhigh(:)), cat(1,Glow(:),Ghigh(:)), cat(1,Blow(:),Bhigh(:))] ); %// create colormap
colorbar;
set(gca, 'YDir','reverse')
axis image
xticks(1:num_net); yticks(1:num_net)
xticklabels(network_names); yticklabels(network_names)
xtickangle(45); set(gca,'TickLength',[0 0])
saveas(gcf,strcat(figure_path,parc_name,'_fig2d_heatmap.svg'));
% Positive coefficients
pos_net_out = zeros(num_net,num_net);
for net1 = 1:num_net
for net2 = 1:num_net
if pos_net_out(net1,net2) ~=0
pos_net_out(net2,net1) = 0;
else
tmp = 0;
counter = 0;
for row = 1:size(net_coords_all{net1,net2},1)
tmp = tmp + cont_pos(net_coords_all{net1,net2}(row,1),net_coords_all{net1,net2}(row,2));
if cont_pos(net_coords_all{net1,net2}(row,1),net_coords_all{net1,net2}(row,2)) ~=0
counter = counter + 1;
end
end
pos_net_out(net2,net1) = tmp/counter;
end
end
end
clear counter
pos_net_out(isnan(pos_net_out)) = 0; pos_net_out(isinf(pos_net_out)) = 0;
pos_net_out(:,13) = 0;
pos_net_out(13,:) = 0;
figure
ax(2) = gca; s = pcolor(pos_net_out); pbaspect([1 1 1]);
caxis([0,max(max(pos_net_out))]); colormin = [255 255 255]; colormax = [200 50 50]; colorneutral = [227 152 152];
Rlow = linspace(colormin(1)/255,colorneutral(1)/255,n); Rhigh = linspace(colorneutral(1)/255,colormax(1)/255,n);
Blow = linspace(colormin(3)/255,colorneutral(3)/255,n); Bhigh = linspace(colorneutral(3)/255,colormax(3)/255,n);
Glow = linspace(colormin(2)/255,colorneutral(2)/255,n); Ghigh = linspace(colorneutral(2)/255,colormax(2)/255,n);
colormap(ax(2),[cat(1,Rlow(:),Rhigh(:)), cat(1,Glow(:),Ghigh(:)), cat(1,Blow(:),Bhigh(:))] ); %// create colormap
c = colorbar;
xticks(1:num_net); yticks(1:num_net)
s.LineWidth = 1;
set(gca, 'YDir','reverse')
axis image