-
Notifications
You must be signed in to change notification settings - Fork 1
/
plot_corrmat.m
1798 lines (1724 loc) · 72.5 KB
/
plot_corrmat.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
function [corrmat, h_corrmat, h_colorbar] = plot_corrmat(timeSeries, varargin)
% PLOT_CORRMAT % Calculate and/or Plot Correlation Matrix
%
% Author: Elliot Layden, 2016
%
% Inputs:
% timeSeries, Multiple input types allowed:
% 1. char/string full-path-to or filename of
% a 4D NIfTI (.nii,.nii.gz) or .img/.hdr pair (specified
% referencing only the .img file)
% -note: It is best practice to specify the full
% path to the file, using,
% e.g. "timeSeries = fullfile(<path>,<filename>);".
% 2. a cell array wherein each outer cell contains data
% for one scan/subject (i.e., # cells == #
% scans/subjects); each outer cell may contain the
% char/string full-path-to or filename of a 4D fMRI
% image, as in option (1), or alternatively, each outer
% cell may contain an inner cell array, wherein each
% inner cell contains the char/string full-path-to or
% filename of an individual 3D fMRI image, comprising
% part of the full 4D fMRI time series (i.e., # inner
% cells == # time points);
% -note: if multiple scans/subjects are specified,
% ROI power spectrums for each can be plotted, the
% average power spectrum and 95% confidence interval
% can be displayed, and the consistency can be gauged.
% 3. timeSeries can be specified as a column vector or as
% a 2D matrix, wherein each column of the matrix
% represents a distinct time series (useful for either
% the case of multiple ROIs or multiple scans/subjects).
% 4. timeSeries can be specified as an already
% loaded image structure as returned by load_nii or
% load_untouch_nii, or as a 4D time series image matrix.
% -note: this option is incompatible with multiple
% time series
% 5. if timeSeries is not specified or is specified as
% empty [], the program will request the user to first
% specify the # of scans/subjects, then the user will be
% prompted to select the appropriate files (either as
% multiple 3D images per scan/subject, or as a single 4D
% image per scan/subject).
%
% Name-Value Pair Arguments:
%
% 'ROI', -Character/String: specified as a filename for a 3D
% image of ROIs, denoted by sequential integer voxel
% values. -Cell Array: wherein each cell contains the
% subscript indices of an ROI (row: voxel #; column:
% [x,y,z] subscripts).
%
% 'nuisance', a cell array (one cell per scan) containing a 2D
% matrix (rows = time points; cols = nuisance
% variables); this option can be useful, e.g., if one
% needs to regress out subject-specific motion
% parameters from the data, or if one wants to
% investigate the effect made on correlation matrices
% by different preprocessing options
%
% 'detrend', integer value specifying whether and what type of
% detrending is desired before computation of the
% power spectrum, wherein 0 = no detrending, 1 =
% linear detrend, 2 = quadratic detrend (default = 0)
% -note: quadratic detrending removes both linear and
% quadratic trends
%
% 'bandpass', vector specified as [HighPass,LowPass], wherein
% HighPass = the lower frequency limit (Hz), and
% LowPass = the upper frequency limit (Hz); bandpass
% filtering is implemented using Brainstorm's
% bst_bandpass_filtfilt method (John Mosher, Francois
% Tadel, 2014)
%
% 'Fs', numeric: sampling frequency (Hz) = 1 / sample_time (s)
% -this only needs to be specified if bandpass
% filtering is requested
%
% 'plot', TRUE(1)/FALSE(0); (default: TRUE)
%
% 'title', string denoting title (default: 'Correlations')
%
% 'labels', a cell array of ROI labels, such as
% {'ROI_1','ROI_2',...etc.}
%
% 'colormap', char/string: 'jet','hot','pink',etc.; this can be
% edited interactively as well
%
% 'which_scan', integer specifying which scan number to display
% correlation matrix for, or 0 to display Grand Mean
% (default is 0 if multiple scans, 1 otherwise)
%
% 'sort_ind', numeric vector: indices for sorting rows & cols of
% correlation matrices
%
% 'print', characer/string: 'path\filename'; if specified, the
% fully initialized figure will automatically print
% to the filename specified; possible extensions
% (.png, .tiff, .bmp) are automatically detected from
% from the filename; if not specified, defaults to
% .png (in 300 dpi)
%
% 'corrmat', this input specifies an already calculated
% correlation matrix which is input solely for
% plotting purposes; in this case, "Plot" and
% "Preprocessing" menus will be disabled;
% 'timeSeries' input should be specified as an empty
% matrix ('[]') in this case; Other valid inputs for
% corrmat mode include 'plot','title','labels',
% 'colormap,'sort_ind', and 'print'
%
% 'insert_axes', this specifies a pre-existing axes object in which
% to plot the corrmat, rather than generate a new
% axes and figure
%
%
% Preprocessing Types:
% 1 = raw; 2 = linear detrend; 3 = quadratic detrend; 4 = bandpass;
% 5 = linear detrend & bandpass; 6 = quadratic detrend & bandpass;
% 7 = nuisance only; 8 = nuisance, linear detrend;
% 9 = nuisance, quadratic detrend; 10 = nuisance, linear detrend, bandpass;
% 11 = nuisance, quadratic detrend, bandpass; 12 = nuisance, bandpass
%
% GUI Options:
%
% FILE MENU:
% Save .mat, this option allows the specification of a .mat
% filename; it writes a single variable 'corrmat',
% a cell aray in which each cell contains the
% correlation matrices for a different preprocessing
% type (see above); within each cell, each
% 3rd-dimension (z) index denotes a different scan,
% wherein the last is the grand mean correlation
% matrix
%
% Export to Workspace, this option allows the specification of a
% workspace variable name, to which the
% currently displayed correlation matrix only
% will be exported
%
% Print, This will print the currently displayed figure as a
% 300 dpi .png, .bmp, or .tiff;
%
% PREPROCESSING MENU: This menu allows the interactive specification and
% viewing of different preprocessing options. Current options are
% marked with an asterisk (*).
% -Note: the order of preprocessing is always
% nuisance regression -> detrend -> bandpass filter, with steps
% skipped or added based on user preferences
%
% DISPLAY MENU: This menu offers a variety of display options, including
% font adjustments for the title, labels, or colorbar tick labels; a
% variety of colormaps and specification of the color axis; and
% enabling/disabling of the colorbar.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get name-value pair arguments:
inputs = varargin;
parsed_inputs = struct('ROI',[],'nuisance',[],'detrend',0,'bandpass',[0,0],...
'Fs',[],'plot',1,'title','','labels',[],'colormap','jet','which_scan',0,...
'sort_ind',[],'print',0,'corrmat',[],'insert_axes',[],'outline',0,...
'label_FontSize',12,'colorbar_FontSize',12); % defaults
poss_input = {'ROI','nuisance','detrend','bandpass','Fs','plot','title',...
'labels','colormap','which_scan','sort_ind','print','corrmat',...
'insert_axes','outline','label_FontSize','colorbar_FontSize'};
input_ind = zeros(1,length(poss_input));
for ixx = 1:length(poss_input)
ixx1 = find(strcmp(poss_input{ixx},inputs));
if ~isempty(ixx1)
input_ind(ixx) = ixx1;
input1 = inputs{input_ind(ixx)+1};
if ixx==1
if (ischar(input1) && exist(input1,'file')==2) || iscell(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
error('Input ''ROI'' was specified incorrectly.')
end
elseif ixx==2
if iscell(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
error(['Invalid input for ''',inputs{input_ind(ixx)},...
'''. Please specify a cell array.'])
end
elseif ixx>2 && ixx<7
if isnumeric(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
error(['Invalid input for ''',inputs{input_ind(ixx)},...
'''. Please specify an integer.'])
end
elseif ixx>=7 && ixx<10
if ischar(input1) || iscell(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
error(['Invalid input for ''',inputs{input_ind(ixx)},...
'''. Please specify character/string.'])
end
elseif ixx>10 && ixx<13
if isnumeric(input1) || ischar(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
error(['Invalid input for ''',inputs{input_ind(ixx)},...
'''. Please specify an integer or file path.'])
end
elseif ixx==13
if ismatrix(input1) && (size(input1,1)==size(input1,2))
parsed_inputs.(poss_input{ixx}) = input1;
else
error(['Invalid input for ''',inputs{input_ind(ixx)},...
'''. Please specify a 2D symmetrical matrix.'])
end
elseif ixx==14
if isgraphics(input1,'axes')
parsed_inputs.(poss_input{ixx}) = input1;
else
warning('Invalid input for ''insert_axes''. Must provide a valid, pre-existing axes handle')
end
elseif ixx==15
if isnumeric(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
warning('Invalid input for ''outline''. Must provide a logical/numeric 1 or 0.')
end
elseif ixx==16 || ixx==17
if isnumeric(input1)
parsed_inputs.(poss_input{ixx}) = input1;
else
warning('Invalid input for ''outline''. Must provide a logical/numeric 1 or 0.')
end
else
error(['Invalid input for ''',inputs{input_ind(ixx)},'''.'])
end
end
end
if isempty(parsed_inputs.corrmat)
non_corrmat_mode = true;
else
non_corrmat_mode = false;
numrois = size(parsed_inputs.corrmat,1);
corrmat = {parsed_inputs.corrmat};
which_scan = 1;
multi_series = false;
curr_data_type = 1;
end
% Check for Valid timeSeries:
extensions={'*.img';'*.nii';'*nii.gz'};
if (nargin < 1 || isempty(timeSeries)) && non_corrmat_mode
% First, determine number of scans:
dlg_title = '# Scans';
prompt = 'How many fMRI scans? '; num_lines = [1,30];
answer = inputdlg(prompt,dlg_title,num_lines);
if isempty(answer)
disp('User cancelled action.');
return;
else
nSeries = str2double(answer(1));
if isempty(nSeries) || isnan(nSeries)
error('Error: You must enter a valid # of scans.')
end
end
% Get User Specification of Time Series for 1:nSeries:
last_funct_dir = pwd; first_dir = last_funct_dir;
timeSeries = cell(1,nSeries);
for i = 1:nSeries
% Get User Input:
cd(last_funct_dir)
[funct_name, funct_path] = uigetfile(extensions,...
sprintf('Scan #%g: Select One 4D Functional or Series of 3D Functionals',i),'MultiSelect','on');
if funct_path==0 % Cancel
return;
else
last_funct_dir = funct_path;
end
if ischar(funct_name); funct_name = {funct_name}; end % if single, still make cell
% Check number of 3D series or single 4D
check_num = numel(funct_name); % # 3D images in series, or 1 4D
if i==1 % check multi_select & nTime only once
if check_num>1
multi_select = true; nTime = check_num;
else
multi_select = false;
end
else
if check_num~=nTime
error('Error: All scans should be of the same duration.')
end
end
% Check extension and re-sort:
[~,~,ext] = fileparts(funct_name{1});
for ix = 1:3
if ~isempty(strfind(extensions{ix},ext))
type = ix; others = setdiff(1:3,ix); break;
end
end
extensions = extensions([type,others]);
% Add to timeSeries variable
if ~multi_select
timeSeries{i} = fullfile(last_funct_dir,funct_name{1});
else
for j = 1:nTime
timeSeries{i}{j} = fullfile(last_funct_dir,funct_name{j});
end
end
end
cd(first_dir)
end
% Check for Valid Fs:
if ~isempty(parsed_inputs.bandpass) && non_corrmat_mode
if isempty(parsed_inputs.Fs) || isnan(parsed_inputs.Fs)
dlg_title = 'Fs';
prompt = 'Enter Sampling Frequency (Fs) [ 1 / Sample Time (Ts) ]: '; num_lines = [1,30];
answer = inputdlg(prompt,dlg_title,num_lines);
if isempty(answer)
disp('User cancelled action.'); return;
else
Fs = str2double(answer(1));
if isempty(Fs) || isnan(Fs)
error('Error: You must enter a valid sampling frequency (Fs) if bandpass filtering is requested.')
end
end
end
end
Fs = parsed_inputs.Fs;
% Load ROIs, if specified:
if non_corrmat_mode
if ~isempty(parsed_inputs.ROI)
if ischar(parsed_inputs.ROI)
load_char_ROI
elseif iscell(parsed_inputs.ROI)
roi_subscripts = parsed_inputs.ROI;
numrois = length(roi_subscripts);
end
else
% Request file selection for ROI image:
[roi_name, roi_path] = uigetfile(extensions,...
'Select 3D ROI Image:','MultiSelect','off');
if roi_path==0 % Cancel
disp('User cancelled action.')
return;
end
if ischar(roi_name)
parsed_inputs.ROI = fullfile(roi_path,roi_name);
load_char_ROI;
end
end
end
function load_char_ROI
try
roi = load_nii(parsed_inputs.ROI);
catch
try
roi = load_untouch_nii(parsed_inputs.ROI);
warning('Non-orthogonal shearing detected in affine matrix of ROI image. Loaded successfully without applying affine.')
catch
error('Error: failed to load ROI image')
end
end
numrois = length(unique(roi.img(roi.img(:)>0)));
fprintf('Image containing %g ROIs successfully loaded.',numrois)
fprintf('%s\r',' ')
% Extract ROI subscript indices:
roi_subscripts = cell(1,numrois);
for jx = 1:numrois
voxind = find(roi.img(:)==jx);
[ind_x,ind_y,ind_z] = ind2sub(size(roi.img),voxind);
roi_subscripts{jx} = [ind_x,ind_y,ind_z];
end
end
% Determine type of input for timeSeries and form time series matrix
% (output: time series matrix (row = timepoints, col = subjects):
if non_corrmat_mode
if isnumeric(timeSeries) && size(timeSeries,3)==1 % NUMERIC VECTOR
[nTime,nSeries] = size(timeSeries);
if nTime==1 && nSeries>1
warning('''timeSeries'' should be specified as a column vector. Assuming here that columns denote time points.')
timeSeries = timeSeries';
elseif nTime>1
sprintf('Detected %g time points and %g time series.',[nTime,nSeries])
end
elseif ischar(timeSeries) || iscell(timeSeries) % char/string or cell
if ischar(timeSeries); timeSeries = {timeSeries}; end
nSeries = length(timeSeries);
% Attempt to load first Image:
disp('Checking timeSeries images...')
try
if ischar(timeSeries{1})
img = load_nii(timeSeries{1});
else
img = load_nii(timeSeries{1}{1});
end
untouch = false;
catch
try
if ischar(timeSeries{1})
img = load_untouch_nii(timeSeries{1});
else
img = load_untouch_nii(timeSeries{1}{1});
end
catch
error('Error: Could not load functional image.')
end
untouch = true;
warning('Non-orthogonal shearing detected in affine matrix. Image successfully loaded without applying affine.')
end
disp('Loading timeSeries images...')
size1 = size(img.img);
% Determine # Time Points:
if ischar(timeSeries{1})
nTime = size(img.img,4);
else
nTime = length(timeSeries{1});
end
% Initialize dataHolder:
dataHolder = cell(1,nSeries);
% Attempt to load timeSeries image(s):
h_wait = waitbar(0,'Loading functional data...');
clear img
for i = 1:nSeries % subject/scan
waitbar(i/nSeries,h_wait);
% Load
if ischar(timeSeries{i}) % 4D images
if untouch
img = load_untouch_nii(timeSeries{i});
else
img = load_nii(timeSeries{i});
end
% Extract Data
for j = 1:numrois
roi_size = size(roi_subscripts{j},1);
voxel_mat = zeros(nTime,roi_size);
for k = 1:roi_size
voxel_mat(:,k) = squeeze(img.img(roi_subscripts{j}(k,1),roi_subscripts{j}(k,2),roi_subscripts{j}(k,3),:));
end
dataHolder{i}(:,j) = mean(voxel_mat,2);
end
elseif iscell(timeSeries{i}) % 3D series
img4D = zeros([size1(1:3),nTime]);
if untouch
for j = 1:nTime
img = load_untouch_nii(timeSeries{i}{j});
img4D(:,:,:,j) = img.img;
end
else
for j = 1:nTime
img = load_nii(timeSeries{i}{j});
img4D(:,:,:,j) = img.img;
end
end
% Extract Data
for j = 1:numrois
roi_size = size(roi_subscripts{j},1);
voxel_mat = zeros(nTime,roi_size);
for k = 1:roi_size
voxel_mat(:,k) = squeeze(img4D(roi_subscripts{j}(k,1),roi_subscripts{j}(k,2),roi_subscripts{j}(k,3),:));
end
dataHolder{i}(:,j) = mean(voxel_mat,2);
end
end
end
timeSeries = dataHolder;
delete(h_wait); clear img dataHolder
elseif isnumeric(timeSeries) && size(timeSeries,3)>1 % 4D numeric matrix
size1 = size(timeSeries); nSeries = 1;
% Initialize dataHolder:
dataHolder = {zeros(nTime,numrois)};
nTime = size1(4);
for j = 1:numrois
roi_size = size(roi_subscripts{j},1);
voxel_mat = zeros(nTime,roi_size);
for k = 1:roi_size
voxel_mat(:,k) = squeeze(timeSeries(roi_subscripts{j}(k,1),roi_subscripts{j}(k,2),roi_subscripts{j}(k,3),:));
end
dataHolder{1}(:,j) = mean(voxel_mat,2);
end
timeSeries = dataHolder;
elseif isstruct(timeSeries) % Image Structure
nSeries = 1;
% Initialize dataHolder:
dataHolder = {zeros(nTime,numrois)};
nTime = size(timeSeries.img,4);
for j = 1:numrois
roi_size = size(roi_subscripts{j},1);
voxel_mat = zeros(nTime,roi_size);
for k = 1:roi_size
voxel_mat(:,k) = squeeze(timeSeries.img(roi_subscripts{j}(k,1),roi_subscripts{j}(k,2),roi_subscripts{j}(k,3),:));
end
dataHolder{1}(:,j) = mean(voxel_mat,2);
end
timeSeries = dataHolder;
end
multi_series = nSeries>1; % true/false
end
%% Initialize:
if non_corrmat_mode
data_types = zeros(1,12); data_types(1) = 1;
data_types_str = {'Raw: ','Linear Detrend: ','Quadratic Detrend: ',...
'Bandpass Filter: ','Linear/Bandpass: ','Quadratic/Bandpass: ',...
'Nuisance Regression: ','Nuisance/Linear: ','Nuisance/Quadratic: ',...
'Nuisance/Linear/Bandpass: ','Nuisance/Quadratic/Bandpass:',...
'Nuisance/Bandpass: '};
% Initialize final time series cell array:
alldata = cell(1,12);
alldata{1} = timeSeries;
for i = 2:12
alldata{i} = cell(1,nSeries);
end
which_scan = parsed_inputs.which_scan; % Grand Mean (0, default); Other scan (1:nSeries)
if which_scan==0
which_scan = nSeries+1;
end
corrmat = cell(1,12);
end
N_cmap = '64';
h_image = 28.1873;
h_colorbar = 71.3747;
h_line = zeros(1,size(corrmat{1},1)); % outline handles
caxis_auto = true;
cmin = -.1; cmax = .1;
labels_on = true;
colorbar_on = true;
FontName = 'Arial'; FontSize = parsed_inputs.label_FontSize; FontWeight = 'normal';
title_FontName = 'Helvetica'; title_FontSize = 11; title_FontWeight = 'bold';
rb3_cmap = false;
main_colormap_selection = 'blue-red';
info_popup = 18.37272;
highlight_on = false;
highlight_color = [1,1,0]; % initialize to yellow
% ROI Indices:
if isempty(parsed_inputs.sort_ind) || (length(parsed_inputs.sort_ind)~=numrois)
sort_ind = 1:numrois;
warning('''sort_ind'' should be of length equal to the # of ROIs')
else
sort_ind = parsed_inputs.sort_ind;
end
alpha_data = triu(ones(numrois),1);
alpha_data2 = tril(ones(numrois),-1);
% Positioning:
screen_res = get(0,'MonitorPositions'); % get(0,'ScreenSize');
figure_pos = [.236*screen_res(3),.063*screen_res(4),...
.537*screen_res(3), .86*screen_res(4)];
if isempty(parsed_inputs.insert_axes)
ax_pos = [.14,.1,.78,.88]; % leave x at .45 to leave room when large decimals on y-axis
colorbar_pos = [ax_pos(1),.034,ax_pos(3),.06];
else
ax_pos = get(parsed_inputs.insert_axes,'Position');
colorbar_pos = [ax_pos(1),ax_pos(2)-.075,ax_pos(3),.06];
end
ax_nocolorbar_pos = [.11,.01,.84,.97];
% Labels:
if isempty(parsed_inputs.labels) % default labels:
parsed_inputs.labels = cell(1,numrois);
for i = 1:numrois
parsed_inputs.labels{i} = sprintf('ROI %02g',i);
end
end
%% Preprocessing:
if non_corrmat_mode
% Determine whether to perform preprocessing initially:
if ~isempty(parsed_inputs.nuisance)
nuisance_regression;
nuisance_on = true; nuisance_curr = true;
else
nuisance_on = false; nuisance_curr = false;
end
if parsed_inputs.detrend
perform_detrend(parsed_inputs.detrend);
end
if any(parsed_inputs.bandpass~=0)
perform_bandpass(1);
bandpass_on = true;
else
bandpass_on = false;
end
determine_curr_data_type;
for iter1 = find(data_types)
calc_corrs(iter1);
end
% Preprocessing order: denoise -> detrend -> bandpass
end
% Nuisance Regression: perform_nuisance_regression(parsed_inputs.nuisance)
function nuisance_regression
data_types(7) = 1;
for ixxx = 1:nSeries
X = parsed_inputs.nuisance{ixxx};
% Check for constant term
if ~any(all(X==1)); X = [ones(size(X,1),1),X]; end %#ok
for jxxx = 1:numrois
[~,~,alldata{7}{ixxx}(:,jxxx)] = regress(alldata{1}{ixxx}(:,jxxx),X);
end
end
end
% Detrending: perform_detrend(parsed_inputs.detrend)
function perform_detrend(type)
switch type
case 1 % parsed_inputs.detrend==1
if ~data_types(2)
disp('Performing linear detrending.')
data_types(2) = 1;
for ixxx = 1:nSeries
alldata{2}{ixxx} = detrend(alldata{1}{ixxx});
end
end
if ~data_types(8)
disp('Performing linear detrending on denoised data.')
data_types(8) = 1;
for ixxx = 1:nSeries
alldata{8}{ixxx} = detrend(alldata{7}{ixxx});
end
end
case 2 % parsed_inputs.detrend==2
if ~data_types(3)
disp('Performing quadratic detrending.')
x = (1:nTime)';
for ixxx = 1:nSeries
for jxxx = 1:numrois
p = polyfit(x,alldata{1}{ixxx}(:,jxxx),2);
predicted = polyval(p,x);
alldata{3}{ixxx}(:,jxxx) = alldata{1}{ixxx}(:,jxxx)-predicted;
end
end
data_types(3) = 1;
end
if ~data_types(9)
disp('Performing quadratic detrending on denoised data.')
x = (1:nTime)';
for ixxx = 1:nSeries
for jxxx = 1:numrois
p = polyfit(x,alldata{7}{ixxx}(:,jxxx),2);
predicted = polyval(p,x);
alldata{9}{ixxx}(:,jxxx) = alldata{7}{ixxx}(:,jxxx)-predicted;
end
end
data_types(9) = 1;
end
end
end
% Bandpass
function perform_bandpass(initial)
if all(parsed_inputs.bandpass==0)
% Prompt User:
prompt = {'Min Frequency (Hz):','Max Frequency (Hz):'};
dlg_title = 'Band-Pass Settings'; num_lines = [1,40;1,40]; defaultans = {'.008','.1'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
if isempty(answer); disp('User cancelled action.'); return; end
if ~any(isnan(str2double(answer)))
parsed_inputs.bandpass(1) = str2double(answer{1});
parsed_inputs.bandpass(2) = str2double(answer{2});
end
end
if parsed_inputs.bandpass(1) <= (.1*(Fs/4))
parsed_inputs.bandpass(1) = (.1*(Fs/4))+.0001;
warning('HighPass set too low for sampling frequency (Fs), adjusted to %.4g Hz',parsed_inputs.bandpass(1))
end
if parsed_inputs.bandpass(2) >= (Fs/2)
parsed_inputs.bandpass(2) = (Fs/2)-.001;
warning('LowPass set too high for sampling frequency (Fs), adjusted to %.4g Hz',parsed_inputs.bandpass(2))
end
for iter = find((data_types(1:3)-data_types(4:6))==1)
for ixxx = 1:nSeries
try
[bandpassed,~,~] = bst_bandpass_filtfilt(alldata{iter}{ixxx}',Fs,...
parsed_inputs.bandpass(1), parsed_inputs.bandpass(2), 0, 'iir');
catch
error('Bandpass Filter Error: Check if ''Fs'' was specified accurately.')
end
alldata{iter+3}{ixxx} = bandpassed';
end
if ~initial
calc_corrs(iter+3);
end
data_types(iter+3) = 1;
end
% Now repeat for nuisance regression:
if nuisance_on
iter2 = [12, 10, 11];
ind_nuis = find((data_types([7, 8, 9])-data_types(iter2))==1);
for iter = ind_nuis
out_ind = iter2(iter);
for ixxx = 1:nSeries
try
[bandpassed,~,~] = bst_bandpass_filtfilt(alldata{iter+6}{ixxx}',Fs,...
parsed_inputs.bandpass(1), parsed_inputs.bandpass(2), 0, 'iir');
catch
error('Bandpass Filter Error: Check if ''Fs'' was specified accurately.')
end
alldata{out_ind}{ixxx} = bandpassed';
end
if ~initial
calc_corrs(out_ind);
end
data_types(out_ind) = 1;
end
end
end
%% Calculate CorrMat
% Calculate Mean CorrMat if Multiple Series:
% 1 = raw, 2 = linear detrend, 3 = quadratic detrend, 4 = bandpass,
% 5 = linear detrend & bandpass, 6 = quadratic detrend & bandpass
function calc_corrs(type)
corrmat{type} = zeros(numrois,numrois,nSeries+1);
for iter2 = 1:nSeries
r = corr(alldata{type}{iter2});
r(logical(eye(numrois))) = nan; % null main diagonal
corrmat{type}(:,:,iter2) = r;
end
% Grand Mean:
corrmat{type}(:,:,nSeries+1) = mean(corrmat{type},3);
end
%% Plot
if parsed_inputs.plot
% Initialize Figure
if isempty(parsed_inputs.insert_axes)
h_corrmat = figure('Position',figure_pos,'MenuBar','none',...
'Name',parsed_inputs.title,'NumberTitle','on','Color',[1,1,1]); % [.8,.88,.98]
else
h_corrmat = get(parsed_inputs.insert_axes,'Parent');
end
file_menu = uimenu(h_corrmat,'Label','File');
if non_corrmat_mode
uimenu(file_menu,'Label','Save .mat','Callback',@save_mat);
uimenu(file_menu,'Label','Export to Workspace','Callback',@export_var);
end
uimenu(file_menu,'Label','Save Figure','Callback',@save_figure_callback);
uimenu(file_menu,'Label','Print','Callback',{@print_callback,0});
% Plot Menus
if multi_series && non_corrmat_mode
plots_menu = uimenu(h_corrmat,'Label','Plot');
h_which_scan_menu = zeros(1,nSeries+1);
which_scan_labels = cell(1,nSeries+1);
for iter3 = 1:nSeries
which_scan_labels{iter3} = sprintf('Scan %g',iter3);
h_which_scan_menu(iter3) = uimenu(plots_menu,'Label',which_scan_labels{iter3},'Callback',{@which_scan_callback,iter3});
end
which_scan_labels{nSeries+1} = 'Grand Mean';
if which_scan==nSeries+1 % if not zero (grand mean)
h_which_scan_menu(nSeries+1) = uimenu(plots_menu,'Label',[which_scan_labels{which_scan},' *'],'Callback',{@which_scan_callback,nSeries+1});
else % default, use Grand Mean
h_which_scan_menu(nSeries+1) = uimenu(plots_menu,'Label',which_scan_labels{which_scan},'Callback',{@which_scan_callback,nSeries+1});
end
else
which_scan = 1;
end
if non_corrmat_mode
% Preprocessing Menu
preprocessing_menu = uimenu(h_corrmat,'Label','Preprocessing');
if nuisance_on
nuisance_menu = uimenu(preprocessing_menu,'Label','Nuisance Regression *','Callback',@nuisance_callback);
end
detrend_menu = uimenu(preprocessing_menu,'Label','Detrending');
detrend0_menu = uimenu(detrend_menu,'Label','None','Callback',{@change_detrend_callback,0});
detrend1_menu = uimenu(detrend_menu,'Label','Linear','Callback',{@change_detrend_callback,1});
detrend2_menu = uimenu(detrend_menu,'Label','Quadratic','Callback',{@change_detrend_callback,2});
if parsed_inputs.detrend==0
detrend0_menu.Label = 'None *';
elseif parsed_inputs.detrend==1
detrend1_menu.Label = 'Linear *';
elseif parsed_inputs.detrend==2
detrend2_menu.Label = 'Quadratic *';
end
% Add bandpass
bandpass_menu = uimenu(preprocessing_menu,'Label','Bandpass');
if any(data_types(4:6))
bandpass_on_menu = uimenu(bandpass_menu,'Label','On *','Callback',{@change_bandpass_callback,1});
bandpass_off_menu = uimenu(bandpass_menu,'Label','Off','Callback',{@change_bandpass_callback,0});
else
bandpass_on_menu = uimenu(bandpass_menu,'Label','On','Callback',{@change_bandpass_callback,1});
bandpass_off_menu = uimenu(bandpass_menu,'Label','Off *','Callback',{@change_bandpass_callback,0});
end
uimenu(bandpass_menu,'Label','Respecify','Callback',{@change_bandpass_callback,2});
end
% Display Menu:
display_menu = uimenu(h_corrmat,'Label','Display');
colormap_menu = uimenu(display_menu,'Label','Colormap');
uimenu(colormap_menu,'Label','blue-red','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','blue-red (2)','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','blue-red (3)','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','jet','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','hot','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','cool','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','gray','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','hsv','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','bone','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','copper','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','spring','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','summer','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','winter','Callback',@colormap_callback);
uimenu(colormap_menu,'Label','pink','Callback',@colormap_callback);
caxis_menu = uimenu(display_menu,'Label','Color Axis');
uimenu(caxis_menu,'Label','Automatic','Callback',{@caxis_callback,1});
uimenu(caxis_menu,'Label','Specify...','Callback',{@caxis_callback,0});
title_menu = uimenu(display_menu,'Label','Title');
uimenu(title_menu,'Label','Edit','Callback',@title_edit);
uimenu(title_menu,'Label','FontName','Callback',{@title_font,1});
uimenu(title_menu,'Label','FontSize','Callback',{@title_font,2});
title_font_bold = uimenu(title_menu,'Label','FontWeight');
uimenu(title_font_bold,'Label','Normal','Callback',{@title_font,3});
uimenu(title_font_bold,'Label','Bold','Callback',{@title_font,4});
labels_menu = uimenu(display_menu,'Label','Labels');
uimenu(labels_menu,'Label','Enable/Disable','Callback',{@labels_callback,1});
labels_font = uimenu(labels_menu,'Label','Font');
uimenu(labels_font,'Label','FontName','Callback',{@labels_callback,2});
uimenu(labels_font,'Label','FontSize','Callback',{@labels_callback,3});
font_bold = uimenu(labels_font,'Label','FontWeight');
uimenu(font_bold,'Label','Normal','Callback',{@labels_callback,4});
uimenu(font_bold,'Label','Bold','Callback',{@labels_callback,5});
colorbar_menu = uimenu(display_menu,'Label','ColorBar');
uimenu(colorbar_menu,'Label','Enable/Disable','Callback',{@colorbar_callback,1});
colorbar_font_menu = uimenu(colorbar_menu,'Label','Font');
uimenu(colorbar_font_menu,'Label','FontName','Callback',{@colorbar_callback,2});
uimenu(colorbar_font_menu,'Label','FontSize','Callback',{@colorbar_callback,3});
colorbar_font_bold = uimenu(colorbar_font_menu,'Label','FontWeight');
uimenu(colorbar_font_bold,'Label','Normal','Callback',{@colorbar_callback,4});
uimenu(colorbar_font_bold,'Label','Bold','Callback',{@colorbar_callback,5});
highlight_menu = uimenu(display_menu,'Label','Highlight');
choose_color_menu = uimenu(highlight_menu,'Label','Choose Color');
uimenu(choose_color_menu,'Label','Yellow','Callback',{@highlight_callback,1});
uimenu(choose_color_menu,'Label','Green','Callback',{@highlight_callback,2});
uimenu(choose_color_menu,'Label','Magenta','Callback',{@highlight_callback,3});
uimenu(choose_color_menu,'Label','Cyan','Callback',{@highlight_callback,4});
uimenu(choose_color_menu,'Label','Red','Callback',{@highlight_callback,5});
uimenu(choose_color_menu,'Label','Blue','Callback',{@highlight_callback,6});
uimenu(choose_color_menu,'Label','White','Callback',{@highlight_callback,7});
uimenu(choose_color_menu,'Label','Black','Callback',{@highlight_callback,8});
% uimenu(highlight_menu,'Label','Connect Selection','Callback',@connect_callback);
uimenu(highlight_menu,'Label','Disable','Callback',{@highlight_callback,0});
outline_menu = uimenu(display_menu,'Label','Outline','Checked','off','Callback',@change_outline);
if isempty(parsed_inputs.insert_axes)
% Initialize Axes
ax = axes('Position',ax_pos,'XDir','reverse','YDir','reverse','XLim',[.5,numrois+.5],...
'YLim',[.5,numrois-.5],'Box','off','XTick',[],'YTick',[],'Visible','off');
hold(ax,'on'); view(-90,90);
else
ax = parsed_inputs.insert_axes;
set(ax,'Box','off','XTick',[],'YTick',[],'XDir','reverse','YDir','reverse',...
'XLim',[.5,numrois+.5],'YLim',[.5,numrois-.5],'Visible','off'); % 'XDir','reverse','YDir','reverse','XLim',[.5,numrois+.5],'YLim',[.5,numrois-.5]
hold(ax,'on'); view(ax,-90,90);
end
% Make Axes Unclickable (Unselectable):
% set(ax,'PickableParts','none')
% Colormap:
% main_colormap = eval([parsed_inputs.colormap,'(',N_cmap,')']);
% main_colormap = redblue(str2double(N_cmap));
% main_colormap = redbluecmap(11);
% main_colormap = bluewhitered(str2double(N_cmap),cmin,cmax);
% colormap(ax,main_colormap);
% Add Title:
h_title = title(ax,parsed_inputs.title,'Visible','on','Units',...
'normalized','PickableParts','all','FontName',title_FontName,...
'FontSize',title_FontSize,'FontWeight',title_FontWeight);
center_axes = (ax_pos(3)+ax_pos(1))-.5*ax_pos(3); % axes center in norm fig units
adjust1 = (.5-center_axes)/ax_pos(3); % adjustment needed in axes units
title_pos = get(h_title,'Position');
title_pos(1) = .5 - .5*title_pos(3) + adjust1; title_pos(2) = .99;
if isempty(parsed_inputs.insert_axes)
set(h_title,'Position',title_pos);
end
% Update Plot:
update_plot(1,curr_data_type);
end
% If 'outline' input is specified:
if parsed_inputs.outline
hObject = struct('Checked','off');
change_outline(hObject)
end
% If 'print' input is specified:
if parsed_inputs.print
print_callback([],[],1);
end
function update_plot(initialize,curr_data_type,~)
if ~initialize && isgraphics(h_image,'image')
cla(ax); delete(h_colorbar);
end
% Determine CData Idx:
imdata = corrmat{curr_data_type}(:,:,which_scan);
if caxis_auto
cmin = min(imdata(:)); cmax = max(imdata(:)); % min & max color value
end
if cmin==cmax; cmax = cmin + 1; end
if nargin==3 %&& update_cmap % update cmap:
colormap_callback([],[],[]);
end
if rb3_cmap
m = 11;
else
m = str2double(N_cmap);
end
idx1 = min(m,round((m-1)*(imdata-cmin)/(cmax-cmin))+1);
idx1(idx1<=0) = 1; % assure no negative or 0 indices
main_colorbar_lim = [min(idx1(:)),max(idx1(:))];
if main_colorbar_lim(1)>=main_colorbar_lim(2)
main_colorbar_lim(2) = main_colorbar_lim(2)+1;
end
% Create Image:
h_image = image('Parent',ax,'CData',idx1(sort_ind,sort_ind),'AlphaDataMapping','none',...
'AlphaData',alpha_data,'ButtonDownFcn',@click_corrmat);
if colorbar_on
axes(ax);
h_colorbar = colorbar('southoutside','Position',colorbar_pos);
% Set Colorbar Ticks:
h_colorbar.Limits = main_colorbar_lim;
h_colorbar.LimitsMode = 'manual';
h_colorbar.FontName = 'Arial';
h_colorbar.FontSize = parsed_inputs.colorbar_FontSize;
h_colorbar.FontWeight = 'bold';
colorbar_main_cvec = linspace(cmin,cmax,m);
if (cmax-cmin)>(.15*m) % if colorbar ticks should be integers
colorbar_main_cvec = round(colorbar_main_cvec);
h_colorbar.TickLabels = cellstr(sprintf('%1g\n',...
colorbar_main_cvec(h_colorbar.Ticks)));
else
h_colorbar.TickLabels = cellstr(sprintf('%4.2g\n',...
colorbar_main_cvec(h_colorbar.Ticks)));
end
end
% Colormap:
if initialize
main_colormap = bluewhitered(str2double(N_cmap),cmin,cmax);
colormap(ax,main_colormap);
end
% Add Labels:
if labels_on
for l = 2:numrois
text(l,.42,parsed_inputs.labels{sort_ind(l)},'FontName',FontName,...
'FontSize',FontSize,'FontWeight',FontWeight,...
'HorizontalAlignment','right','Parent',ax);
end
for l = 1:numrois-1
text(l+.2,l-.45,parsed_inputs.labels{sort_ind(l)},'FontName',FontName,... % .25, .4
'FontSize',FontSize,'FontWeight',FontWeight,'Parent',ax);
end
end
% Outline
if strcmp(get(outline_menu,'Checked'),'on')
outline_menu.Checked = 'off';
change_outline(outline_menu)
end
end
%% Callbacks:
rect_count = 0; h_rect = 12.3399;
function click_corrmat(~,event,~)
click_ind = round(event.IntersectionPoint(1:2));
if ~highlight_on && alpha_data2(click_ind(1),click_ind(2))
if non_corrmat_mode
% Get Data:
stats = cell(1,sum(data_types)+1);
stats{1} = [parsed_inputs.labels{sort_ind(click_ind(1))},...
' to ',parsed_inputs.labels{sort_ind(click_ind(2))}];
count = 1;
for ixxx = find(data_types)
count = count+1;
r1 = corrmat{ixxx}(sort_ind(click_ind(1)),sort_ind(click_ind(2)),which_scan);
r1 = round(r1*100); r1 = r1*.01; % correct number of sig digits
str = sprintf('%2g',r1);
if r1>0
stats{count} = [data_types_str{ixxx},'r = ',str(2:end)];
else
stats{count} = [data_types_str{ixxx},'r = -',str(3:end)];
end
end
else
stats = {};
r1 = corrmat{1}(sort_ind(click_ind(1)),sort_ind(click_ind(2)));
stats{1} = sprintf('%2.3g',r1);
end
if ishandle(info_popup); delete(info_popup); end % Only allow one at a time
reversed = numrois:-1:1;
info_pos = [click_ind(2)/numrois,reversed(click_ind(1))/numrois,.05,.05];