-
Notifications
You must be signed in to change notification settings - Fork 1
/
CAP_TB.m
3544 lines (2628 loc) · 123 KB
/
CAP_TB.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
%% This is the main script containing the routines necessary for the use
% of the co-activation pattern analysis (CAP) toolbox known as TbCAPs
%
% Original scripts implemented and written by Thomas A. W. Bolton, from
% the Medical Image Processing Laboratory (MIP:Lab), EPFL, Switzerland
%
% For concerns, please write to thomas.arthur.bolton@gmail.com
%
% Version 1.0 (November 9th 2018): first usable version of the toolbox, and
% start of use by a few local members from the Lausanne/Geneva Universities
%
% Version 2.0 (January 10th 2020): first publicly released version of the
% toolbox with extended functionalities
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% SECTION 0: SETTING UP GUI %%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Handles the opening of the toolbox window (set by MATLAB)
function varargout = CAP_TB(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @CAP_TB_OpeningFcn, ...
'gui_OutputFcn', @CAP_TB_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
function CAP_TB_OpeningFcn(hObject, eventdata, handles, varargin)
%%%%%%%%%%%%%%%%%%%%
% Path and other miscellaneous settings
% Adds the paths to the subfolders of the toolbox that will be important
% for the plotting and the analysis
addpath(genpath('./Plotting'));
addpath(genpath('./Analysis'));
addpath(genpath('./DefaultData'));
% Sets warnings off
warning('off');
% Choose default command line output for CAP_TB
handles.output = hObject;
%%%%%%%%%%%%%%%%%%%%
% Data loading
% TC will contain the time courses of the subjects from the different
% populations (cell array, each cell with size n_TP x n_masked_voxels)
handles.TC = {};
% FD contains the traces of framewise displacement for the subjects (n_TP x
% n_subj per cell of the array, one cell per dataset)
handles.FD = {};
% Information on the NIFTI files from which the data originate, used in
% order to plot brain slices in the interface
handles.brain_info = {};
% mask specifies the voxels that will be retained for the analyses
handles.mask = {};
% Number of datasets added to the interface. A dataset is defined as a
% population of subjects from the same experimental group (e.g., an
% ensemble of subjects suffering from the same disorder)
handles.n_datasets = 0;
handles.ReferencePopulation = 1;
% Stores the number of subjects that have been loaded
handles.n_subjects = {};
% TP and VOX contain the number of time points (of frames) and of brain
% voxels that are present in the loaded datasets. Those values are
% initialized at -inf, and then take the values of the first file that is
% being loaded if that file looks reasonable dimensionally speaking. In the
% scripts below, it is assumed that all subject populations loaded have a
% similar number of time points and of voxels
handles.SubjSize.TP = -inf;
handles.SubjSize.VOX = -inf;
mask_string{1} = 'Grey matter';
mask_string{2} = 'Whole-brain';
mask_string{3} = 'White matter';
mask_string{4} = 'CSF';
set(handles.MaskPopup,'String',mask_string);
clear mask_string
handles.prefix = 'sw';
% Loads and sets the brain underlay used for plotting purposes
Underlay = load_nii('Underlay.nii');
Underlay_mat = [Underlay.hdr.hist.srow_x; Underlay.hdr.hist.srow_y; Underlay.hdr.hist.srow_z; 0 0 0 1];
Underlay_dim = Underlay.hdr.dime.dim;
Underlay_dim = Underlay_dim(2:4);
handles.Underlay_info.dim = Underlay_dim;
handles.Underlay_info.mat = Underlay_mat;
clear Underlay
clear Underlay_dim
clear Underlay_mat
load('brain.mat');
assignin('base','brain', brain);
handles.brain = brain;
clear brain
% Handles for the TR and whether it is a reasonable value; the latter
% boolean is used to plot some axes as a function of time instead of
% samples
handles.TR = -inf;
handles.isTROK = false;
%%%%%%%%%%%%%%%%%%%%
% Seed selection and seed maps
% Seed(s) used for the analysis
handles.seed = [];
% Because there can be more than one seed, we create a vector that will
% encompass the multiple information in several colors
handles.seed_display = [];
% Handle to verify whether the amount of seeds has been entered well, how
% many seeds there are, and the type of computation to run on the seeds
handles.isSeedOK = false;
% Number of different seeds
handles.n_seed = 1;
handles.SeedType = 'Average';
% One average map of correlation is computed across subjects and can be
% displayed as a sanity check
handles.AvgSeedMap = [];
%%%%%%%%%%%%%%%%%%%%
% Time points selection
% Motion threshold for scrubbing (in [mm])
handles.Tmot = 0.5;
% Threshold for frame selection in the analysis
handles.T = 0.5;
% Sets the right text header in front of the frame selection threshold box
% (threshold or retention percentage)
if get(handles.TRadio,'Value')
set(handles.TText,'String','T [-]');
handles.SelMode = 'Threshold';
else
set(handles.TText,'String','P [%]');
handles.SelMode = 'Percentage';
end
handles.is_seed_free = 0;
% Denotes the type of frames (activation, deactivation or both) to use for
% selecting time points. There can be at most three different seeds
handles.SignMatrix = [1 0; 1 0; 1 0];
% Activation and deactivation frames kept and that should enter the
% clustering stage
handles.Xonp = {};
handles.Xonn = {};
% Percentage of frames retained for CAP analysis (discarding both the
% baseline time points and the scrubbed time points)
handles.RetainedPercentage = {};
% Indices of the frames that have been retained (i.e., when do they occur in
% the full time course), of baseline frames, and of scrubbed frames
handles.FrameIndices = {};
handles.idx_sep_seeds = {};
%%%%%%%%%%%%%%%%%%%%
% CAP analysis
handles.is_consensus_clustering = 0;
handles.ConsensusQuality = [];
handles.Consensus = [];
% Max number of clusters to verify with consensus clustering
handles.Kmax = 12;
% Percentage of items to use for the consensus clustering folds
handles.PCC = 80;
% Number of times that clustering is run
handles.n_rep = 20;
% Percentage voxels to keep for clustering (positive - Pp - and negative -
% Pn - ones)
handles.Pp = 100;
handles.Pn = 100;
% Number of clusters to use in the analysis
handles.K = 5;
% Indices of the CAP to which frames from the reference population and from
% the other populations are assigned
handles.idx = {};
% Value of correlation of the control group frame that is the Tper-th least
% close to its CAP
handles.CorrDist = [];
% Contains the CAPs
handles.CAP = [];
handles.Disp = [];
% Contains the standard deviation for the CAPs
handles.STDCAP = [];
% Percentile threshold used in frame assignment
handles.percentile = 5;
%%%%%%%%%%%%%%%%%%%%
% Metrics
% Will contain the metrics
% State matrix (n_subjects x n_time points)
handles.TPM = {};
% State counts (raw and frac)
handles.Counts = {};
% Number of times entering a state
handles.Number = {};
% Average duration within a state
handles.Avg_Duration = {};
% Duration of all the excursions within a state
handles.Duration = {};
% New more recently introduced graph theoretical metrics
handles.From_Baseline = {};
handles.To_Baseline = {};
handles.Baseline_resilience = {};
handles.Resilience = {};
handles.Betweenness = {};
handles.kin = {};
handles.kout = {};
% Transition probabilities
handles.TM = {};
% Cumulative sum of states
handles.TPMCum = {};
% Seed fractions
handles.sfrac = [];
% Number of each type of frame per subject
handles.SubjectEntries = {};
%%%%%%%%%%%%%%%%%%%%
% General utilities
% Log containing the different events summoned from the toolbox
handles.Log = {};
% Colors used in plotting of all populations
handles.PopColor{1} = [255,255,180; 219,224,252; 188,252,188; 230,230,230]/255;
handles.PopColor{2} = [130,48,48; 51,75,163; 59,113,86; 0, 0, 0]/255;
% Project title, by default 'Untitled'
handles.project_title = 'Untitled';
% Directory to which data is to be saved (initially loaded as ./SavedData)
handles.savedir = fullfile(pwd,'SavedData');
set(handles.SaveFolderText,'String',handles.savedir);
% Update handles structure
guidata(hObject, handles);
function varargout = CAP_TB_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% SECTION 1: LOADING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Mask Button Click
% Executes when inputing a new mask file; either the user properly enters
% the data, and a mask is created accordingly, or a default is used
% otherwise
function MaskButton_Callback(hObject, eventdata, handles)
% try
% % Selects the folders where to look (should be the ones just before the
% % 'anat' vs 'func' distinction)
% ToMask = spm_select(Inf,'dir','Select what to compute mask from (root directories)...');
%
% % Iterating across these folders to generate our mask...
% for i = 1:size(ToMask,1)
%
% % Current file path
% tmp = ToMask(i,:);
%
% % We need to determine the header for our data at hand, and we
% % do so if we are considering the first folder inputed
% if i == 1
%
% % Selects all the functional files that match our criteria
% % (prefix 'sw' meaning smoothed MNI space data)
% FFiles = cellstr(spm_select('List',fullfile(tmp,'func'),['^' handles.prefix '.*\.' 'nii' '$']));
%
% % We read the header of the first one to get the data
% % resolution
% handles.brain_info{handles.n_datasets+1} = spm_vol(fullfile(tmp,'func',FFiles{1}));
%
% % We initialise our mask as a 3D volume
% mask_final = logical(ones(handles.brain_info{handles.n_datasets+1}.dim));
% end
%
% % Gets the grey matter data
% SFile = cellstr(spm_select('List',fullfile(tmp,'anat'),['^' 'wc1' '.*\.' 'nii' '$']));
% tmp_GM = spm_vol(fullfile(tmp,'anat',SFile{1}));
% tmp_GMvol = spm_read_vols(tmp_GM);
%
% % Converts into functional resolution
% tmp_GMvol2 = CAP_V2V(tmp_GMvol,tmp_GM.dim,tmp_GM.mat,handles.brain_info{handles.n_datasets+1}.dim,handles.brain_info{handles.n_datasets+1}.mat);
%
% % Binarises
% tmp_GMvol2 = logical(tmp_GMvol2);
%
% % We will, every time, only keep the voxels that are present
% % across all subjects
% mask_final = mask_final & tmp_GMvol2;
% end
%
% % Filling in the mask variable for the dataset at hand as a 1D
% % logical vector
% handles.mask{handles.n_datasets+1} = mask_final(:);
%
% % The button is turned to blue and data stored
% handles.Log = CAP_AddToLog(handles.Log,'New mask generated for the analysis',{sum(handles.mask{handles.n_datasets+1}),size(ToMask,1)},{'Number of voxels','Number of subjects computed from'});
% set(hObject,'BackgroundColor', [101,140,196]/255);
%
% set(handles.DataButton,'Enable','on');
% set(hObject,'Enable','off');
% If there is a problem, we instead ask the user
ToMask = spm_select(Inf,'dir','Please select a directory with functional volumes of any subject...');
% Current file path
tmp = ToMask(1,:);
% Selects all the functional files that match our criteria
% (prefix 'sw' meaning MNI space data)
FFiles = cellstr(spm_select('List',fullfile(tmp),['^' handles.prefix '.*\.' 'nii' '$']));
% We read the header of the first one to get the data
% resolution
try
handles.brain_info{handles.n_datasets+1} = spm_vol(fullfile(tmp,FFiles{1}));
switch get(handles.MaskPopup,'Value')
%GM
case 1
a = spm_vol(fullfile('.','DefaultData','Default_mask.nii'));
% Whole-brain
case 2
a = spm_vol(fullfile('.','DefaultData','BrainMask.nii'));
% White matter
case 3
a = spm_vol(fullfile('.','DefaultData','WhiteMask.nii'));
% CSF
case 4
a = spm_vol(fullfile('.','DefaultData','CerebroMask.nii'));
end
b = spm_read_vols(a);
b(b < 0.9) = 0;
b(b >= 0.9) = 1;
maskf = CAP_V2V(b,a.dim,a.mat,handles.brain_info{handles.n_datasets+1}.dim,handles.brain_info{handles.n_datasets+1}.mat);
% Filling accordingly
handles.mask{handles.n_datasets+1} = logical(maskf(:));
tmp = get(handles.MaskPopup,'String');
handles.Log = CAP_AddToLog(handles.Log,'New default mask generated',{tmp{get(handles.MaskPopup,'Value')},sum(handles.mask{handles.n_datasets+1})},{'Type of mask','Number of voxels'});
set(hObject,'BackgroundColor', [101,140,196]/255);
set(handles.DataButton,'Enable','on');
set(hObject,'Enable','off');
% If we enter here, it means even the default mask generation
% failed, in which case we want to clear everything and have the
% toolbox restarted
catch
errordlg('Error in attempting to create default mask!');
handles = ClearDataButton_Callback(hObject, eventdata, handles);
end
% Update handles structure
guidata(hObject, handles);
%% Data Button Click
% Executes when adding a subject population (clicking on 'A2. Load data')
function DataButton_Callback(hObject, eventdata, handles)
% The user selects the data of interest for the group that should be
% constructed
Data_OI = spm_select(Inf,'dir','Select the directories containing the functional data to analyse within the assessed group...');
% Number of subjects (or runs) considered
handles.n_subjects{handles.n_datasets+1} = size(Data_OI,1);
try
% We now want to update the FD and TC variables by going through all
% the subjects to add to the considered group...
for i = 1:size(Data_OI,1)
disp(['Currently preparing the data from run ',num2str(i),'...']);
% As before, the "sw" prefix is looked for
FFiles = cellstr(spm_select('List',fullfile(Data_OI(i,:)),['^' handles.prefix '.*\.' 'nii' '$']));
% Functional files are read one after the other to build
% tmp_data
tmp_data = [];
for t = 1:length(FFiles)
tmp1 = spm_vol(fullfile(Data_OI(i,:),FFiles{t}));
tmp2 = spm_read_vols(tmp1);
tmp3 = tmp2(:);
tmp_data = [tmp_data;tmp3(handles.mask{1})'];
end
% Z-scoring is performed within the toolbox
% tmp_data = detrend(tmp_data);
% tmp_data = zscore(tmp_data);
tmp_data = (tmp_data-repmat(mean(tmp_data),size(tmp_data,1),1)) ./ repmat(std(tmp_data),size(tmp_data,1),1);
tmp_data(isnan(tmp_data)) = 0;
% The ready-to-analyse data is put in TC
handles.TC{handles.n_datasets+1}{i} = tmp_data;
clear tmp_data
try
% Look for the text file with motion parameters (should be the
% first text file found)
MFile = cellstr(spm_select('List',fullfile(Data_OI(i,:)),['.*\.' 'txt' '$']));
% Computes framewise displacement and fills the FD matrix
% accordingly
handles.FD{handles.n_datasets+1}(:,i) = CAP_ComputeFD(fullfile(Data_OI(i,:),MFile{1}));
catch
handles.FD{handles.n_datasets+1}(:,i) = zeros(length(FFiles),1);
handles.Log = CAP_AddToLog(handles.Log,'Could not process motion text file; assuming zero movement...');
end
end
% Some commands are run only for the first dataset that we add; we
% compute and store the number of voxels and the number of time
% points, as well as the number of subjects
if handles.n_datasets == 0
handles.SubjSize.VOX = size(handles.TC{1}{1},2);
handles.SubjSize.TP = size(handles.TC{1}{1},1);
end
% Sets the text label about data dimensions
set(handles.Dimensionality_Text, 'String', [num2str(handles.SubjSize.TP),...
' frames x ',num2str(handles.SubjSize.VOX),' voxels (',...
strjoin(arrayfun(@(x) num2str(x),cell2mat(handles.n_subjects),...
'UniformOutput',false),'+'),')']);
% We can now enable the seed selection
set(handles.SeedButton,'Enable','on');
set(handles.SeedFreeButton,'Enable','on');
set(handles.TMotText,'Visible','on');
set(handles.TMotEdit,'Visible','on');
% set(handles.TText,'Visible','on');
% set(handles.TEdit,'Visible','on');
% set(handles.PRadio,'Visible','on');
% set(handles.TRadio,'Visible','on');
% set(handles.uibuttongroup7,'Visible','on');
% Also, we can now color the button in green
set(hObject,'BackgroundColor', [101,140,196]/255);
% If we are loading the first dataset, we convert the underlay
% to the resolution of the functional data for plotting
if handles.n_datasets == 0
% The brain variable now contains a good resolution
% underlay that can directly be overlapped with the
% functional data
handles.brain = CAP_V2V(handles.brain,handles.Underlay_info.dim,...
handles.Underlay_info.mat,handles.brain_info{1}.dim,handles.brain_info{1}.mat);
else
% Also creates the brain_info and mask for the new pop
handles.mask{handles.n_datasets+1} = handles.mask{1};
handles.brain_info{handles.n_datasets+1} = handles.brain_info{1};
set(handles.CAP_TP,'Visible','on');
set(handles.Percentile_Edit,'Visible','on');
% If we are loading one more dataset on top of the
% first one, then we clear the subsequent locations of the
% toolbox
handles = ClearSection2(eventdata,handles);
handles = ClearSection3(eventdata,handles);
handles = ClearSection4(eventdata,handles);
% We then want to enable the assignment of frames
set(handles.AssignButton,'Enable','on');
set(handles.SeedButton,'Enable','on');
set(handles.SeedFreeButton,'Enable','on');
set(handles.TMotText,'Visible','on');
set(handles.TMotEdit,'Visible','on');
end
% We we are loading our final population, then we disable the
% option to enter more still
if handles.n_datasets == 3
set(handles.DataButton,'Enable','off');
end
handles.Log = CAP_AddToLog(handles.Log,'Data correctly loaded',...
{handles.n_datasets+1},{'Population index'});
% We increment handles.n_datasets
handles.n_datasets = handles.n_datasets + 1;
catch
errordlg('Could not load subject population!');
end
% Update handles structure
guidata(hObject, handles);
%% TR Textbox Interaction
% Executes when we go to the TR field to add the TR of the experiment
function TR_Entry_Callback(hObject, eventdata, handles)
% If the TR takes a reasonable value, then we validate it; we enable values
% larger than 0
if (~isempty(str2double(get(hObject,'String')))) && ...
(str2double(get(hObject,'String')) > 0)
handles.TR = str2double(get(hObject,'String'));
set(hObject,'BackgroundColor', [101,140,196]/255);
handles.isTROK = true;
handles.Log = CAP_AddToLog(handles.Log,'Correct value of TR entered',{handles.TR},{'TR'});
% Else, the TR value is not accepted
else
set(hObject,'BackgroundColor', [204,146,146]/255);
handles.isTROK = false;
end
guidata(hObject, handles);
% Executes during creation of the TR textbox
function handles = TR_Entry_CreateFcn(hObject, eventdata, handles)
set(hObject,'Enable','off');
set(hObject,'String','Click to enter...');
set(hObject,'FontAngle','italic');
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','r');
end
guidata(hObject, handles);
% Executes when clicking on the TR text space
function TR_Entry_ButtonDownFcn(hObject, eventdata, handles)
set(hObject,'Enable','on');
set(hObject,'String','');
set(hObject,'FontAngle','normal');
uicontrol(hObject);
guidata(hObject, handles);
function PrefixText_Callback(hObject, eventdata, handles)
if (~isempty(get(hObject,'String')))
handles.prefix = get(hObject,'String');
set(hObject,'BackgroundColor', [101,140,196]/255);
handles.Log = CAP_AddToLog(handles.Log,'Prefix for data loading set',{handles.prefix},{'Prefix'});
% Else, the TR value is not accepted
else
set(hObject,'BackgroundColor', [204,146,146]/255);
end
guidata(hObject, handles);
function handles = PrefixText_CreateFcn(hObject, eventdata, handles)
set(hObject,'Enable','off');
set(hObject,'String','Click to enter...');
set(hObject,'FontAngle','italic');
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','r');
end
guidata(hObject, handles);
function PrefixText_ButtonDownFcn(hObject, eventdata, handles)
set(hObject,'Enable','on');
set(hObject,'String','');
set(hObject,'FontAngle','normal');
uicontrol(hObject);
guidata(hObject, handles);
% --- Executes on selection change in MaskPopup.
function MaskPopup_Callback(hObject, eventdata, handles)
tmp = get(hObject,'String');
handles.Log = CAP_AddToLog(handles.Log,'Modified the type of mask to use',{tmp{get(hObject,'Value')}},{'Mask type'});
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function MaskPopup_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
guidata(hObject, handles);
%% Data saving and loading
% The functions below are summoned when the user wishes to save his/her
% data into a MATLAB structure, or to load previously processed data and
% attempt clustering computations and CAP generation
function SaveFolderButton_Callback(hObject, eventdata, handles)
% Selection of a directory
[dirname]=uigetdir('*.*','Please select a save directory');
handles.savedir = dirname;
% If the user has indeed chosen a directory, we set it as the new save
% folder
if ~isequal(dirname,0)
set(handles.SaveFolderText,'String',handles.savedir);
set(hObject,'BackgroundColor', [101,140,196]/255);
handles.Log = CAP_AddToLog(handles.Log,'Save folder changed',...
{handles.savedir},...
{'Save folder'});
else
errordlg('Please select a directory !');
end
guidata(hObject,handles);
% Upon clicking on the 'SAVE' button, the data will be saved entirely under
% a file name partly chosen by the user and partly depending on the present
% date and time
function SaveButton_Callback(hObject, eventdata, handles)
% General information on the project
OverallInfo.ProjectTitle = handles.project_title;
OverallInfo.NumberTimePoints = handles.SubjSize.TP;
OverallInfo.NumberVoxels = handles.SubjSize.VOX;
OverallInfo.NumberSubjects = handles.n_subjects;
OverallInfo.TR = handles.TR;
Parameters.Inputs.DataHeader = handles.brain_info;
Parameters.Inputs.Mask = handles.mask;
Parameters.Inputs.Seeds = handles.seed;
Parameters.SpatioTemporalSelection.IsSeedFree = handles.is_seed_free;
Parameters.SpatioTemporalSelection.NumberSeeds = handles.n_seed;
Parameters.SpatioTemporalSelection.TypeEventRetainedPerSeed = handles.SignMatrix;
Parameters.SpatioTemporalSelection.SeedType = handles.SeedType;
Parameters.SpatioTemporalSelection.MotionThreshold = handles.Tmot;
Parameters.SpatioTemporalSelection.SelectionMode = handles.SelMode;
Parameters.SpatioTemporalSelection.FrameSelectionParameter = handles.T;
Parameters.KMeansClustering.IsConsensusRun = handles.is_consensus_clustering;
Parameters.KMeansClustering.MaxClusterNumber = handles.Kmax;
Parameters.KMeansClustering.PercentageDataPerFold = handles.PCC;
Parameters.KMeansClustering.NumberRepetitions = handles.n_rep;
Parameters.KMeansClustering.NumberClusters = handles.K;
Parameters.KMeansClustering.PercentagePositiveValuedVoxelsClustered = handles.Pp;
Parameters.KMeansClustering.PercentageNegativeValuedVoxelsClustered = handles.Pn;
Outputs.SpatioTemporalSelection.RetainedFramesPerSeed = handles.idx_sep_seeds;
Outputs.SpatioTemporalSelection.PercentageRetainedFrames = handles.RetainedPercentage;
Outputs.SpatioTemporalSelection.AverageCorrelationMap = handles.AvgSeedMap;
Outputs.KMeansClustering.ConsensusQuality = handles.ConsensusQuality;
Outputs.KMeansClustering.CoActivationPatternsDispersion = handles.Disp;
Outputs.KMeansClustering.CoActivationPatterns = handles.CAP;
Outputs.KMeansClustering.CoActivationPatternsZScored = CAP_Zscore(handles.CAP);
Outputs.KMeansClustering.CoActivationPatternsSTD = handles.STDCAP;
Outputs.KMeansClustering.AssignmentsToCAPs = handles.idx;
Outputs.Metrics.CAPExpressionIndices = handles.TPM;
Outputs.Metrics.Occurrences = handles.Counts;
Outputs.Metrics.NumberEntries = handles.Number;
Outputs.Metrics.AverageExpressionDuration = handles.Avg_Duration;
Outputs.Metrics.AllExpressionDurations = handles.Duration;
Outputs.Metrics.TransitionProbabilities = handles.TM;
Outputs.Metrics.FractionCAPFramesPerSeedCombination = handles.sfrac;
Outputs.Metrics.CAPEntriesFromBaseline = handles.From_Baseline;
Outputs.Metrics.CAPExitsToBaseline = handles.To_Baseline;
Outputs.Metrics.CAPResilience = handles.Resilience;
Outputs.Metrics.BaselineResilience = handles.Baseline_resilience;
Outputs.Metrics.BetweennessCentrality = handles.Betweenness;
Outputs.Metrics.CAPInDegree = handles.kin;
Outputs.Metrics.CAPOutDegree = handles.kout;
Outputs.Metrics.SubjectCounts = handles.SubjectEntries;
HeavyOutputs.SpatioTemporalSelection.ClusteredFrames = handles.Xonp;
HeavyOutputs.KMeansClustering.Consensus = handles.Consensus;
fancy_name = [handles.project_title];
% Saves NIFTI files storing the CAPs in MNI space
CAPToNIFTI(handles.CAP,...
handles.mask{handles.ReferencePopulation},handles.brain_info{handles.ReferencePopulation},...
handles.savedir,['CAP_NIFTI_',fancy_name]);
CAPToNIFTI(CAP_Zscore(handles.CAP),...
handles.mask{handles.ReferencePopulation},handles.brain_info{handles.ReferencePopulation},...
handles.savedir,['CAP_NIFTI_ZScored_',fancy_name]);
% Saves the different variables from the program
if get(handles.SaveCheckbox,'Value')
save(fullfile(handles.savedir,fancy_name),'OverallInfo','Parameters','Outputs','HeavyOutputs','-v7.3');
else
save(fullfile(handles.savedir,fancy_name),'OverallInfo','Parameters','Outputs','-v7.3');
end
% Adds the save process to the log
handles.Log = CAP_AddToLog(handles.Log,'Data saved');
% Writes a log .txt file with what has been done so far
file_ID = fopen(fullfile(handles.savedir,[fancy_name,'.txt']),'wt');
for i = 1:length(handles.Log)
for j = 1:length(handles.Log{i})
fprintf(file_ID,[handles.Log{i}{j},'\n']);
end
fprintf(file_ID,'\n');
end
fclose(file_ID);
% Clears the structure now that it has been saved
clear Outputs
clear HeavyOutputs
clear Parameters
clear OverallInfo
guidata(hObject,handles);
function SaveCheckbox_Callback(hObject, eventdata, handles)
guidata(hObject,handles);
% Executes when pressing on the 'CLEAR' button for data loading; supposed
% to set everything back to normal (when the window opened)
function handles = ClearDataButton_Callback(hObject, eventdata, handles)
handles = ClearSection1(eventdata,handles);
handles = ClearSection2(eventdata,handles);
handles = ClearSection3(eventdata,handles);
handles = ClearSection4(eventdata,handles);
% Loads and sets the brain underlay used for plotting purposes
Underlay = load_nii('Underlay.nii');
Underlay_mat = [Underlay.hdr.hist.srow_x; Underlay.hdr.hist.srow_y; Underlay.hdr.hist.srow_z; 0 0 0 1];
Underlay_dim = Underlay.hdr.dime.dim;
Underlay_dim = Underlay_dim(2:4);
handles.Underlay_info.dim = Underlay_dim;
handles.Underlay_info.mat = Underlay_mat;
clear Underlay
clear Underlay_dim
clear Underlay_mat
load('brain.mat');
assignin('base','brain', brain);
handles.brain = brain;
clear brain
handles.Log = CAP_AddToLog(handles.Log,'Data cleared');
guidata(hObject, handles);
% Clears the content of section 1 only
function handles = ClearSection1(eventdata, handles)
% Makes 'A. Load data' red again
set(handles.DataButton,'BackgroundColor',[204,146,146]/255);
set(handles.DataButton,'Enable','off');
% Resets the mask button
set(handles.MaskButton,'BackgroundColor',[204,146,146]/255);
set(handles.MaskButton,'Enable','on');
% Same for Save folder button
set(handles.SaveFolderButton,'BackgroundColor',[204,146,146]/255);
% Resets the time point and voxel parameters
handles.SubjSize.TP = -inf;
handles.SubjSize.VOX = -inf;
set(handles.MaskPopup,'Value',1);
handles.prefix = 'sw';
handles = PrefixText_CreateFcn(handles.PrefixText, eventdata, handles);
% Resets the TR
handles.TR = -inf;
handles.isTROK = false;
% Resets the reference population
handles.ReferencePopulation = 1;
handles = ProjectTitleText_CreateFcn(handles.ProjectTitleText,eventdata,handles);
% Also resets the number of subjects variable and associated text
set(handles.Dimensionality_Text, 'String','_ frames x _ voxels (_)');
handles.n_subjects = {};
% Resets the number of datasets entered to 0
handles.n_datasets = 0;
% Empties the data, motion, brain information and mask variables
handles.TC = {};
handles.FD = {};
handles.mask = {};
handles.brain_info = {};
% Resets the text related to motion and data files
handles.SubjNames = {};
handles.MotName = {};
% Resets the title and save folder information
handles.Log = {};
% Project title, by default 'Untitled'
handles.project_title = 'Untitled';
set(handles.SaveCheckbox,'Value',0);
% Directory to which data is to be saved (initially loaded as ./SavedData)
handles.savedir = fullfile(pwd,'SavedData');
set(handles.SaveFolderText,'String',handles.savedir);
%%%%%%%%%% Putting the loading part (bottom) back to normal %%%%%%%%%%%
% We also want to set the TR textbox back to its initial state
handles = TR_Entry_CreateFcn(handles.TR_Entry, eventdata, handles);
% Clears the content of section 2 only
function handles = ClearSection2(eventdata, handles)
% Stores the type of frames to retain for each seed
handles.SignMatrix = [1 0; 1 0; 1 0];
% Puts back the seed buttons information to original state
handles.seed = [];
set(handles.SeedButton,'BackgroundColor',[204,146,146]/255);
set(handles.SeedButton,'Enable','off');
set(handles.SeedFreeButton,'Enable','off');
set(handles.PlotSeedButton,'Enable','off');
set(handles.PlotSeedButton,'Visible','off');
% Seed label entries set invisible
set(handles.S_SEED1,'Visible','off');
set(handles.S_SEED2,'Visible','off');
set(handles.S_SEED3,'Visible','off');
handles.is_seed_free = 0;
% Removes graph display for the seed
cla(handles.SeedGraphX);
cla(handles.SeedGraphZ);
set(handles.SeedGraphX,'Visible','off');
set(handles.SeedGraphZ,'Visible','off');
set(handles.SliderX,'Visible','off');
set(handles.SliderZ,'Visible','off');
set(handles.XCoordText,'Visible','off');
set(handles.ZCoordText,'Visible','off');
%%%%%%%%%%%% Putting the seed map part back to normal %%%%%%%%%%%%%%%%%%%
% Resets the variable containing the seed maps of the subjects
handles.AvgSeedMap = [];
% Not clickable anymore
set(handles.SeedMapPushButton,'Enable','off');
set(handles.SeedMapPushButton,'Visible','off');
% Resets colorbar display
handles = ResetGraphDisplay(handles.ColorbarSeed,handles);
% Makes the slider and the text linked to slider of the seed map threshold
% back to invisible
set(handles.TSeed_Slider,'Visible','off');
set(handles.TSeed,'Visible','off');
% Resets graphs with seed map plots
handles = ResetGraphDisplay(handles.SeedMapX,handles);
handles = ResetGraphDisplay(handles.SeedMapZ,handles);
% Resets associated sliders
set(handles.SeedMapSliderX,'Visible','off');
set(handles.SeedMapSliderZ,'Visible','off');
% Resets associated slider texts
set(handles.SeedMap_SliderX,'Visible','off');
set(handles.SeedMap_SliderZ,'Visible','off');
% Resets the circles plot
handles = ResetGraphDisplay(handles.FancyCircles,handles);
% Sets the associated text back to invisible
set(handles.SeedPlusText,'Visible','off');
set(handles.SeedMinusText,'Visible','off');
set(handles.Seed1Text,'Visible','off');
set(handles.Seed2Text,'Visible','off');
set(handles.Seed3Text,'Visible','off');
% Puts the seed boxes back to not visible
set(handles.CheckS1POS,'Visible','off');
set(handles.CheckS2POS,'Visible','off');
set(handles.CheckS3POS,'Visible','off');
set(handles.CheckS1NEG,'Visible','off');
set(handles.CheckS2NEG,'Visible','off');
set(handles.CheckS3NEG,'Visible','off');
set(handles.TPSelectionButton,'Enable','off');
set(handles.TPSelectionButton,'Visible','off');
set(handles.PRadio,'Visible','off');
set(handles.TRadio,'Visible','off');
set(handles.uibuttongroup7,'Visible','off');
set(handles.TText,'Visible','off');
set(handles.TMotText,'Visible','off');