-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtfce_estimate_stat.m
2980 lines (2517 loc) · 89.2 KB
/
tfce_estimate_stat.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 tfce_estimate_stat(job)
% main TFCE function for estimating TFCE statistics
%
% FORMAT tfce_estimate_stat(job)
% job - job from tbx_cfg_tfce
%
% job fields:
% data
%
% nproc
% 0 - no multi-threading
% x - number of processors for multi-threading
%
% nuisance_method
% method to deal with nuisance variables
% 0 - Draper-Stoneman
% 1 - Freedman-Lane
% 2 - Smith
%
% single-threaded
% 0 - multi-threaded TFCE estimation
% 1 - single-threaded TFCE estimation
%
% conspec.contrasts
% Inf - interactive selection of contrast
% x - index of contrast(s)
%
% mask
% mask for restricting TFCE estimation (SVC)
%
% tbss
% TBSS weighting
%
% ______________________________________________________________________
%
% Christian Gaser
% Structural Brain Mapping Group (https://neuro-jena.github.io)
% Departments of Neurology and Psychiatry
% Jena University Hospital
% ______________________________________________________________________
global old_method_stat
% disable parallel processing for only one SPM.mat file
if numel(job.data) == 1
job.nproc = 0;
end
% split job and data into separate processes to save computation time
if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) && exist('cat_parallelize','file')
cat_parallelize(job,mfilename,'data');
return
% or run though all data step-by-step
elseif numel(job.data)>1
data = job.data;
for i=1:numel(job.data)
job = rmfield(job,'data');
job.process_index = i;
job.data{1} = data{i};
tfce_estimate_stat(job)
end
return
end
% Use tail approximation from the Gamma distribution for corrected P-values
use_gamma_tail_approximation = true;
tail_approximation_wo_unpermuted_data = false;
% single-threaded?
singlethreaded = job.singlethreaded;
% convert to z-statistic
convert_to_z = false;
% option to stop estimation if no FWE-corrected result was found after defined number of permutations
stop_if_no_FWEeffects_found = Inf;
% use (too liberal) method for estimating maximum statistic from old release
% r184 for compatibility purposes only that was estimating max/min statistics
% only inside pos./neg. effects and not both
if isfield(job,'old_method_stat')
old_method_stat = job.old_method_stat;
elseif exist('old_method_stat','var') && isempty(old_method_stat)
old_method_stat = false;
end
if old_method_stat
fprintf('Use old method from r184 to estimate maximum statistics which might be too liberal.\n');
end
% save null distribution
save_null_distribution = true;
% method to deal with nuisance variables
% 0 - Draper-Stoneman
% 1 - Freedman-Lane
% 2 - Smith
nuisance_method = job.nuisance_method;
% display permuted design matrix (otherwise show t distribution)
show_permuted_designmatrix = true;
% allow to test permutations without analyzing data
% test mode is automatically chosen if only a SPM.mat is available
% without any data
test_mode = false;
% define stepsize for tfce
n_steps_tfce = 100;
% colors and alpha levels
col = [0.25 0 0; 1 0 0; 1 0.75 0];
alpha = [0.05 0.01 0.001];
% give same results each time
if exist('rng','file') == 2
rng('default')
rng(0)
else
rand('state',0);
end
% tolerance for comparing real numbers
tol = 1e-4;
% check spm version
if ~strcmp(spm('ver'),'SPM12')
error('Please use any TFCE version < r215 that still supports SPM8.')
end
% indicate if voxel-wise covariates were modeled
[pt,nm] = fileparts(job.data{1});
is_vSPM = strcmp(nm,'vSPM');
load(job.data{1});
cwd = fileparts(job.data{1});
%-Check that model has been estimated
if ~isfield(SPM, 'xVol')
str = { 'This model has not been estimated.';...
'Would you like to estimate it now?'};
if spm_input(str,1,'bd','yes|no',[1,0],1)
cd(cwd)
SPM = spm_spm(SPM);
else
return
end
end
Ic0 = job.conspec.contrasts;
% if just one contrast is defined use this and skip interactive selection
if (numel(Ic0) == 1) && ~isfinite(Ic0) && isfield(SPM,'xCon') && (numel(SPM.xCon) == 1)
Ic0 = 1;
end
% check whether contrast are defined
if (numel(Ic0) == 1)
if ~isfinite(Ic0) || ~isfield(SPM,'xCon') || (isfield(SPM,'xCon') && isempty(SPM.xCon))
[Ic0,xCon] = spm_conman(SPM,'T&F',Inf,...
' Select contrast(s)...',' ',1);
SPM.xCon = xCon;
end
end
% for default SPM.mat results has to be called first
if isempty(SPM.xCon(Ic0(1)).eidf) && ~is_vSPM
fprintf('You have to call results first.\n');
cat_spm_results_ui('Setup',SPM);
load(job.data{1});
end
% check that no temporal filter was used
if isstruct(SPM.xX.K)
fprintf('ERROR: No first level analysis with temporal correlations allowed.\n');
return
end
% get some parameters from SPM
xX = SPM.xX;
VY = SPM.xY.VY;
n_data = size(xX.X,1);
% sometimes xX.iB and xX.iH are not correct and cannot be used to reliably recognize the design
xX = correct_xX(xX);
% check whether voxel-wise covariate is defined
voxel_covariate = 0;
for i = 1:numel(SPM.xC)
if isfield(SPM.xC(i),'P') && ~isempty(SPM.xC(i).P)
voxel_covariate = i;
fprintf('Voxel-wise covariate found.\n');
end
end
% find exchangeability block labels for longitudinal designs (paired t-test, flexible factorial)
repeated_anova = ~isempty(xX.iB);
if repeated_anova
[rw,cl] = find(xX.I == length(xX.iB)); % find column which codes subject factor (length(xX.iB) -> n_subj)
exch_block_labels = xX.I(:,cl(1)); % column from above contains the subject factor
% check that labels are defined for each block
for i=1:n_data
groupListed(exch_block_labels(i)) = true;
end
for i = 1:max(exch_block_labels)
if ~groupListed(i)
fprintf('\nError: block %d must be assigned to at least one design row in the blocks file.\n\n',i);
return
end
end
% check whether ate least two time points are available
n_tp = sum(xX.X(:,xX.iB));
if any(n_tp == 1)
fprintf('\nError: You need at least two time points for a longitudinal design for every subjects.\n\n');
return
end
if ~isempty(xX.iC)
fprintf('\Warning: Covariates are not recommended for repeated measures Anova and will not properly work.\n');
fprintf('Please remove any covariates from your longitudinal design.\n\n');
end
fprintf('\nPlease note that permutation is only done within subjects for repeated Anova.\n');
else
exch_block_labels = ones(1,n_data);
end
if ~test_mode
% check for meshes
if spm_mesh_detect(VY)
mesh_detected = true;
else
mesh_detected = false;
end
% set E according to type data
if job.tbss || mesh_detected
E = 1.0; H = 2.0;
else
E = 0.5; H = 2.0;
end
% check for mask image that should exist for any analysis
if exist(fullfile(cwd, 'mask.img'),'file')
file_ext = '.img';
elseif exist(fullfile(cwd, 'mask.nii'),'file')
file_ext = '.nii';
elseif exist(fullfile(cwd, 'mask.gii'),'file')
file_ext = '.gii';
else
fprintf('WARNING: No mask file found. Switch to test mode.\n');
test_mode = true;
end
else
% for test_mode
mesh_detected = false;
end
% check whether 3D filters were selected for surfaces meshes or whether CAT12 is installed
if mesh_detected
if ~exist('spm_cat12','file')
error('For using surface analysis you need to install CAT12.');
end
end
if ~test_mode
% get mask file
if isempty(job.mask)
maskname = fullfile(cwd,['mask' file_ext]);
else
if ~isempty(job.mask{1})
maskname = job.mask{1};
else
maskname = fullfile(cwd,['mask' file_ext]);
end
end
% load mask
try
Vmask = spm_data_hdr_read(maskname);
catch
if mesh_detected
maskname = spm_select(1,'mesh','select surface mask');
else
maskname = spm_select(1,'image','select mask image');
end
Vmask = spm_data_hdr_read(maskname);
end
% if first image was not found you have to select all files again
if ~exist(VY(1).fname,'file')
fprintf('Data not found. Please select data in the order defined in the design matrix.\n');
n = size(SPM.xY.VY,1);
if mesh_detected
P = spm_select(n,'mesh','select surfaces');
else
P = spm_select(n,'image','select images');
end
VY = spm_data_hdr_read(P);
%-Apply gSF to memory-mapped scalefactors to implement scaling
%--------------------------------------------------------------------------
for i = 1:n
VY(i).pinfo(1:2,:) = VY(i).pinfo(1:2,:)*SPM.xGX.gSF(i);
if mesh_detected
if isfield(VY(i).private.private.data{1}.data,'scl_slope')
VY(i).private.private.data{1}.data.scl_slope = ...
VY(i).private.private.data{1}.data.scl_slope * SPM.xGX.gSF(i);
VY(i).private.private.data{1}.data.scl_inter = ...
VY(i).private.private.data{1}.data.scl_inter * SPM.xGX.gSF(i);
end
else
VY(i).private.dat.scl_slope = ...
VY(i).private.dat.scl_slope * SPM.xGX.gSF(i);
VY(i).private.dat.scl_inter = ...
VY(i).private.dat.scl_inter * SPM.xGX.gSF(i);
end
end
SPM.xY.VY = VY;
% update SPM
if size(SPM.xY.VY,1)==n
save(job.data{1},'SPM','-v7.3');
else
fprintf('ERROR: Number of files is not correct\n');
return
end
end
if voxel_covariate
% if first image of voxel-wise covariate was not found you have to select all files again
if ~exist(SPM.xC(voxel_covariate).VC(1).fname,'file')
fprintf('Covariate data not found. Please select covariate data in the order defined in the design matrix.\n');
n = numel(SPM.xC(voxel_covariate).P);
if mesh_detected
P = spm_select(n,'mesh','select surfaces');
else
P = spm_select(n,'image','select images');
end
SPM.xC(voxel_covariate).P = cellstr(P);
if size(P,1)==n
save(job.data{1},'SPM','-v7.3');
else
fprintf('ERROR: Number of files is not correct\n');
return
end
end
VC = spm_data_hdr_read(char(SPM.xC(voxel_covariate).P));
n = numel(VC);
%-Apply gSF to memory-mapped scalefactors to implement scaling for
% voxel-wise covariate
%--------------------------------------------------------------------------
if isfield(SPM.xC(voxel_covariate),'gSF')
for i = 1:n
VC(i).pinfo(1:2,:) = VC(i).pinfo(1:2,:)*SPM.xC(voxel_covariate).gSF(i);
if mesh_detected
if isfield(VC(i).private.private.data{1}.data,'scl_slope')
VC(i).private.private.data{1}.data.scl_slope = ...
VC(i).private.private.data{1}.data.scl_slope * SPM.xC(voxel_covariate).gSF(i);
VC(i).private.private.data{1}.data.scl_inter = ...
VC(i).private.private.data{1}.data.scl_inter * SPM.xC(voxel_covariate).gSF(i);
end
else
VC(i).private.dat.scl_slope = ...
VC(i).private.dat.scl_slope * SPM.xC(voxel_covariate).gSF(i);
VC(i).private.dat.scl_inter = ...
VC(i).private.dat.scl_inter * SPM.xC(voxel_covariate).gSF(i);
end
end
end
SPM.xC(voxel_covariate).VC = VC;
end
% check whether mask images fits to the data
if mesh_detected, dim_index = 1; else dim_index=1:3; end
if sum(sum((Vmask.mat-VY(1).mat).^2)) > 1e-6 || any(Vmask.dim(dim_index) ~= VY(1).dim(dim_index))
error('Mask must have the same dimensions and orientation as the data.');
end
if voxel_covariate
do_resample = false;
if sum(sum((Vmask.mat-VC(1).mat).^2)) > 1e-6 || any(Vmask.dim(dim_index) ~= VC(1).dim(dim_index))
fprintf('Covariate data has different dimensions and orientation as the other data. Thus, your covariate data will be resampled.\n');
fprintf('Please check that your covariate data are co-registered to your other data!\n');
do_resample = true;
end
end
% read mask and data
mask = spm_data_read(Vmask);
ind_mask = find(mask>0);
n = numel(VY);
if ~isempty(ind_mask)
Y = zeros([length(ind_mask) n],'single');
if voxel_covariate
C = zeros([length(ind_mask) n],'single');
meanC = zeros(length(ind_mask),1,'single');
else
C = [];
end
% load data
fprintf('Load data ')
for i=1:n
fprintf('.')
tmp = spm_data_read(VY(i));
Y(:,i) = tmp(ind_mask);
if voxel_covariate
% we need to resample voxel-wise covariate
if do_resample
tmp = zeros(Vmask.dim);
for z=1:Vmask.dim(3)
M = spm_matrix([0 0 z]);
M1 = Vmask(1).mat\VC(i).mat\M;
tmp(:,:,z) = spm_slice_vol(VC(i),M1, Vmask.dim(1:2),[1 0]);
end
else
tmp = spm_data_read(VC(i));
end
tmp = tmp(ind_mask);
C(:,i) = tmp;
meanC = meanC + tmp;
end
end
fprintf('\n')
clear tmp;
% whitening matrix
W = single(full(xX.W));
Y = Y*W;
% mean correct voxel-wise covariate
if voxel_covariate
meanC = meanC/n;
for i=1:n
C(:,i) = C(:,i) - meanC;
end
C = C*W;
end
else
error('Empty mask.');
end
t0 = zeros(Vmask.dim);
t = zeros(Vmask.dim);
end % if ~test_mode
% if just one contrast is defined, use this contrast and skip interactive selection
if isfield(SPM,'xCon') && numel(SPM.xCon) == 1 && ~isfinite(Ic0)
Ic0 = 1;
end
% interactively select contrast(s) if necessary
if numel(Ic0)==1 && ~isfinite(Ic0) && numel(SPM.xCon) > 1
[Ic0,xCon] = spm_conman(SPM,'T&F',Inf,...
' Select contrast(s)...',' ',1);
SPM.xCon = xCon;
end
% go through all contrasts
for con = 1:length(Ic0)
Ic = Ic0(con);
xCon = SPM.xCon(Ic);
n_perm = job.conspec.n_perm(1);
if numel(job.conspec.n_perm) > 1
n_perm_break = job.conspec.n_perm(2);
end
if length(Ic) > 1
fprintf('ERROR: No conjunction allowed.\n');
return
end
fprintf('Use contrast #%d of %s\n',Ic,job.data{1})
% get contrast and name
c0 = xCon.c;
F_contrast_multiple_rows = 0;
% for F-contrasts if rank is 1 we can use the first row
if strcmp(xCon.STAT,'F')
if rank(c0) == 1
c0 = c0(:,1);
else
F_contrast_multiple_rows = 1;
end
end
[indi, indj] = find(c0~=0);
ind_X = unique(indi)';
xCon.ind_X = ind_X;
% check for contrasts that are defined for columns with subject effects
if ~isempty(xX.iB)
if max(ind_X) > min(xX.iB)
fprintf('ERROR: No contrasts on subjects/block effects allowed.\n');
return
end
end
% find exchangeability blocks using contrasts without zero values
exch_blocks = c0(ind_X,:);
n_exch_blocks = length(ind_X);
% recognize effects of interest contrast for F-tests
if F_contrast_multiple_rows && size(exch_blocks,2) == n_exch_blocks
is_eoi = all(all(exch_blocks == eye(n_exch_blocks)));
if is_eoi
n_exch_blocks = 1;
end
end
% check for exchangeability blocks and design matrix
if n_exch_blocks == 1
n_cond = length(find(xX.iH==ind_X)); % check whether the contrast is defined at columns for condition effects
else
n_cond = 0;
n_data_cond = [];
for k=1:length(xX.iH)
n_data_cond = [n_data_cond sum(xX.X(:,xX.iH(k)))];
end
% for F-contrast with multiple rows n_cond is always n_exch_blocks
if F_contrast_multiple_rows && length(xX.iH) > 1
n_cond = n_exch_blocks;
elseif F_contrast_multiple_rows && length(xX.iH) == 1
n_cond = 0;
else
for j=1:n_exch_blocks
col_exch_blocks = find(c0==exch_blocks(j));
for k=1:length(col_exch_blocks)
n_cond = n_cond + length(find(xX.iH==col_exch_blocks(k)));
end
end
end
end
use_half_permutations = 0;
% check if sample size is equal for both conditions
if n_cond == 2
try
% repated Anova or F-test don't allow to use only half of the permutions
if repeated_anova || strcmp(xCon.STAT,'F')
use_half_permutations = 0;
elseif sum(n_data_cond(c0==exch_blocks(1))) == sum(n_data_cond(c0==exch_blocks(2)))
use_half_permutations = 1;
end
end
end
ind_exch_blocks = cell(n_exch_blocks,1);
for j=1:n_exch_blocks
if strcmp(xCon.STAT,'T')
ind_exch_blocks{j} = find(c0==exch_blocks(j));
else
ind_exch_blocks{j} = ind_X(j);
end
end
fprintf('\n');
% check design
interaction_design = false;
switch n_cond
case 0 % correlation
label = 1:n_data;
% we have to correct for some F-contrasts (i.e. effects of interest
% with eyes)
if F_contrast_multiple_rows && is_eoi
is_one = find(any(c0'));
for j=1:numel(is_one)
ind_exch_blocks{j} = is_one(j);
end
ind_exch_blocks = ind_exch_blocks';
end
if n_exch_blocks >= 2 && any(diff(exch_blocks(:))) % # exch_blocks >1 & differential contrast
fprintf('Interaction design between two or more regressors found\n')
interaction_design = true;
% remove all entries where contrast is not defined
% this does not work for all data CG 20200829
% label(all(xX.X(:,ind_X)==0,2)) = [];
else
if repeated_anova
fprintf('Repeated Anova with contrast for covariate found\n');
else
fprintf('Multiple regression design found\n');
end
end
case 1 % one-sample t-test
fprintf('One sample t-test found\n');
% use exchangeability blocks for labels
label = zeros(1,n_data);
for j=1:n_exch_blocks
for k=1:length(ind_exch_blocks{j})
label(xX.X(:,ind_exch_blocks{j}(k))~=0) = j;
end
end
otherwise % Anova with at least 2 groups
if repeated_anova
fprintf('Repeated Anova found\n');
else
fprintf('Anova found\n');
end
% use exchangeability blocks for labels
label = zeros(1,n_data);
for j=1:n_exch_blocks
for k=1:length(ind_exch_blocks{j})
label(xX.X(:,ind_exch_blocks{j}(k))~=0) = j;
end
end
end
fprintf('\n')
% get index for label values > 0
ind_label = find(label > 0);
n_data_with_contrast = length(ind_label);
% estimate # of permutations
% Anova/correlation: n_perm = (n1+n2+...+nk)!/(n1!*n2!*...*nk!)
if n_cond ~=1 % Anova/correlation
n_perm_full = factorial(n_data_with_contrast);
single_subject = 0;
for i=1:n_cond
% check whether only a single subject is in one group
if length(find(label == i)) == 1
single_subject = 1;
end
n_perm_full = n_perm_full/factorial(length(find(label == i)));
end
if isnan(n_perm_full)
% correct number of permutations for large samples when factorial is not working
if (n_cond == 2) && (single_subject == 1)
n_perm_full = n_data_with_contrast;
else
n_perm_full = realmax;
end
end
% find where data are defined for that contrast
if ~isempty(find(xX.iH == ind_X(1), 1))
% first checking whether contrasts are defined for iH
ind_data_defined = find(any(xX.X(:,xX.iH(ind_X)),2));
else
ind_data_defined = find(any(xX.X(:,ind_X),2));
end
% correct ind_label and n_data_with_contrast using ind_data_defined
ind_label = ind_data_defined';
n_data_with_contrast = length(ind_label);
% and restrict exchangeability block labels to those rows
exch_block_labels_data_defined = exch_block_labels(ind_data_defined);
% Repated Anova: n_perm = n_cond1!*n_cond2!*...*n_condk!
% for a full model where each condition is defined for all subjects the easier
% estimation is: n_perm = (n_cond!)^n_subj
% check that no regression analysis inside repeated anova is used
if repeated_anova && n_cond~=0
n_subj = max(exch_block_labels_data_defined);
n_perm_full = 1;
for k=1:n_subj
n_cond_subj = length(find(exch_block_labels_data_defined == k));
n_perm_full = n_perm_full*factorial(n_cond_subj);
end
else
n_perm_full = round(n_perm_full);
end
else % one-sample t-test: n_perm = 2^n
n_perm_full = 2^n_data_with_contrast;
exch_block_labels_data_defined = exch_block_labels;
ind_data_defined = ind_label;
end
% sometimes for F-tests with multiple independent rows the design cannot be fully recognized
% and # of permutations is wrong
if n_perm_full == 1 && F_contrast_multiple_rows
fprintf('ERROR: This F-contrast and type of design with multiple independent rows is not yet supported.\n');
return
end
if n_perm_full < n_perm
fprintf('Warning: Maximum number of possible permutations is lower than defined number of permutations: %d\n',n_perm_full);
end
n_perm = min([n_perm n_perm_full]);
fprintf('Number of permutations: %d\n',n_perm);
if use_half_permutations
fprintf('Equal sample sizes: Use half the number of permutations.\n');
end
fprintf('Exchangeability block/variable: ');
fprintf('%d ',unique(cell2mat(ind_exch_blocks)));
fprintf('\n');
fprintf('# of conditions: %d\n',n_cond);
% Guttman partioning of design matrix into effects of interest X and nuisance variables Z
X = xX.X(:,ind_X);
ind_Z = [xX.iH xX.iC xX.iB xX.iG];
ind_Z(ind_X) = [];
Z = xX.X(:,ind_Z);
Hz = Z*pinv(Z);
Rz = eye(size(X,1)) - Hz;
% if Hz is zero or Ic is empty then no confounds were found and we can skip the time-consuming
% Freedman-Lane permutation
if (all(~any(Hz)) || isempty(xX.iC)) || all(~any(diff(Hz))) || (interaction_design && numel(xX.iC) == numel(ind_X))
exist_nuisance = false;
else
exist_nuisance = true;
end
if ~exist_nuisance && nuisance_method > 0
fprintf('No nuisance variables were found: Use Draper-Stoneman permutation.\n\n');
nuisance_method = 0;
end
if nuisance_method > 0 && repeated_anova
fprintf('Use Draper-Stoneman permutation for repeated measures Anova.\n\n');
nuisance_method = 0;
end
switch nuisance_method
case 0
str_permutation_method = 'Draper-Stoneman';
case 1
str_permutation_method = 'Freedman-Lane';
case 2
str_permutation_method = 'Smith';
end
% name of contrast
c_name0 = deblank(xCon.name);
if test_mode
c_name = '';
else
c_name = sprintf('%s (E=%1.1f H=%1.1f %s) ',c_name0, E, H, str_permutation_method);
end
if ~test_mode
% compute unpermuted t/F-map
if voxel_covariate
% check which pinv-method is faster and use that one for all permutations
X = xX.W*xX.X;
tstart1 = tic;
for i=1:20, pX = pinv(X); end
telapsed1 = toc(tstart1);
tstart2 = tic;
for i=1:20, pX = pinv2(X); end
telapsed2 = toc(tstart2);
if 1.1*telapsed2 < telapsed1
pinv_method = 2;
fprintf('Use faster pinv2 function\n');
else
pinv_method = 1;
end
[t0, df2] = calc_GLM_voxelwise(Y,xX,SPM.xC(voxel_covariate),xCon,ind_mask,VY(1).dim,C,[],ind_X,pinv_method);
else
[t0, df2] = calc_GLM(Y,xX,xCon,ind_mask,VY(1).dim);
end
df1 = size(xCon.c,2);
% transform to z statistic
if convert_to_z
% use faster z-transformation of SPM for T-statistics
if strcmp(xCon.STAT,'T')
t0 = spm_t2z(t0,df2);
else
t0 = palm_gtoz(t0,df1,df2);
end
end
mask_0 = (t0 == 0);
mask_1 = (t0 ~= 0);
mask_P = (t0 > 0);
mask_N = (t0 < 0);
mask_NaN = (mask == 0);
found_P = sum(mask_P(:)) > 0;
found_N = sum(mask_N(:)) > 0;
% remove all NaN and Inf's
t0(isinf(t0) | isnan(t0)) = 0;
% sometimes z-transformation produces neg. values even for F-statistics
if strcmp(xCon.STAT,'F')
t0(t0 < 0) = 0;
end
% get parametric p-values for comparison
tname = sprintf('spm%s_%04d',xCon.STAT,Ic);
tname = fullfile(cwd,[tname file_ext]);
if ~exist(tname,'file') && ~voxel_covariate
spm_contrasts(SPM,Ic);
end
if ~voxel_covariate
Z0 = spm_data_read(tname);
Pt = zeros(size(Z0));
if strcmp(xCon.STAT,'T')
if found_P
Pt(mask_P) = 1-spm_Tcdf(Z0(mask_P),df2);
else
Pt(mask_N) = spm_Tcdf(Z0(mask_N),df2)-1;
end
else
if found_P
Pt(mask_P) = 1-spm_Fcdf(Z0(mask_P),[df1, df2]);
else
Pt(mask_N) = spm_Fcdf(Z0(mask_N),[df1, df2])-1;
end
end
% Check correlation between parametric and non-parametric T/F-values.
% Low correlation points to issues with image mask and we have to use a
cc = corrcoef(Z0(:),t0(:));
mask_shared = Z0 ~= 0;
if cc(1,2) < 0.85 && isempty(job.mask)
% check whether mask size differes and create a shared mask
if sum(Z0(:) ~= 0) ~= sum(t0(:) ~= 0)
fprintf('\nWARNING: Large discrepancy between parametric and non-parametric statistic found (cc=%g) which either points to different image masks or to missing absolute threshold for VBM analysis.\n',cc(1,2));
mask_shared = Z0 ~= 0 & t0 ~=0;
else
fprintf('\nWARNING: Large discrepancy between parametric and non-parametric statistic found (cc=%g) which is likely due to creating parametric statistics in fMRI mode, which slightly handles noise differently.\n',cc(1,2));
end
end
else
mask_shared = ones(size(t0));
end
% get dh for unpermuted map
dh = max(abs(t0(:)))/n_steps_tfce;
% calculate tfce of unpermuted t-map
if mesh_detected
if ~isa(SPM.xVol.G,'gifti')
% check whether path is correct and file exist
if ~exist(SPM.xVol.G,'file')
[pathG,nameG,extG] = spm_fileparts(SPM.xVol.G);
% use new path
if ~isempty(strfind(pathG,'_32k'))
SPM.xVol.G = fullfile(fileparts(which('cat12')),'templates_surfaces_32k',[nameG extG]);
else
SPM.xVol.G = fullfile(fileparts(which('cat12')),'templates_surfaces',[nameG extG]);
end
end
SPM.xVol.G = gifti(SPM.xVol.G);
end
tfce0 = tfce_mesh(SPM.xVol.G.faces, t0, dh, E, H)*dh;
else
% measure computation time to test whether multi-threading causes issues
% start with single-threading for unpermuted data
tstart = tic;
% only estimate neg. tfce values for non-positive t-values
if found_N
tfce0 = tfceMex_pthread(t0,dh,E,H,1,1)*dh;
else
tfce0 = tfceMex_pthread(t0,dh,E,H,0,1)*dh;
end
telapsed = toc(tstart);
end
% prepare output files
Vt = VY(1);
Vt.dt(1) = 16;
Vt.pinfo(1) = 1;
%---------------------------------------------------------------
% save unpermuted t map
%---------------------------------------------------------------
name = sprintf('%s_%04d',xCon.STAT,Ic);
Vt.fname = fullfile(cwd,[name file_ext]);
Vt.descrip = sprintf('%s %04d %s',xCon.STAT,Ic, str_permutation_method);
Vt = spm_data_hdr_write(Vt);
spm_data_write(Vt,t0);
%---------------------------------------------------------------
% save unpermuted TFCE map
%---------------------------------------------------------------
name = sprintf('TFCE_%04d',Ic);
Vt.fname = fullfile(cwd,[name file_ext]);
Vt.descrip = sprintf('TFCE %04d %s',Ic, str_permutation_method);
Vt = spm_data_hdr_write(Vt);
spm_data_write(Vt,tfce0);
% get largest tfce
tfce0_max = max(tfce0(:));
t0_max = max(t0(:));
tfce0_min = min(tfce0(:));
t0_min = min(t0(:));
% prepare countings
tperm = zeros(size(t));
tfceperm = zeros(size(t));
t_min = [];
t_max = [];
t_max_th = [];
tfce_min = [];
tfce_max = [];
tfce_max_th = [];
end % test_mode
% general initialization
try % use try commands to allow batch mode without graphical output
Fgraph = spm_figure('GetWin','Graphics');
spm_figure('Clear',Fgraph);
figure(Fgraph)
h = axes('position',[0.45 0.95 0.1 0.05],'Units','normalized','Parent',...
Fgraph,'Visible','off');
text(0.5,0.6,c_name,...
'FontSize',spm('FontSize',10),...
'FontWeight','Bold',...
'HorizontalAlignment','Center',...
'VerticalAlignment','middle')
text(0.5,0.25,spm_str_manip(spm_fileparts(job.data{1}),'a80'),...
'FontSize',spm('FontSize',8),...
'HorizontalAlignment','Center',...
'VerticalAlignment','middle')
end
% check that label has correct dimension
sz = size(label);
if sz(1)>sz(2)
label = label';
end
stopStatus = false;
if ~test_mode, tfce_progress('Init',n_perm,'Calculating','Permutations'); end
% update interval for progress bar
progress_step = max([1 round(n_perm/100)]);
% Regression design found where contrast is defined for covariate?
if ~isempty(xX.iC) && all(ismember(ind_X,SPM.xX.iC))
ind_label_gt0 = find(label(ind_data_defined) > 0);
else
ind_label_gt0 = find(label > 0);
end
unique_labels = unique(label(ind_label_gt0));
n_unique_labels = length(unique_labels);
perm = 1;
check_validity = false;
while perm<=n_perm
% randomize subject vector
if perm==1 % first permutation is always unpermuted model
if n_cond == 1 % one-sample t-test
rand_label = ones(1,n_data_with_contrast);
label_matrix = rand_label;
else % correlation or Anova