-
Notifications
You must be signed in to change notification settings - Fork 7
/
swe_cp_WB.m
3267 lines (2820 loc) · 121 KB
/
swe_cp_WB.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 swe_cp_WB(SwE)
% Computes statistic and p-value maps for non-parametric analyses.
% =========================================================================
% For a non-parametric SwE analysis with either NIfTI, GIfTI, CIfTI or '.mat' input, the
% following maps are computed:
%
% - swe_{unit}_mask:
% The mask image for the analysis.
%
% - swe_{unit}_{T|F}stat_c{c#}:
% Voxelwise parametric statistic map (T or F) for contrast {c#}.
%
% - swe_{unit}_{zT|xF}stat_c{c#}:
% Voxelwise parametric equivalent statistic map (Z or Chi Squared)
% for contrast {c#}.
%
% - swe_{unit}_{zT|xF}stat-WB_c{c#}:
% Voxelwise non-parametric equivalent statistic map (Z or Chi
% Squared) for contrast {c#}.
%
% - swe_{unit}_{T|F}stat_lp-WB_c{c#}:
% Log10 map of the voxelwise uncorrected P values for contrast
% {c#}.
%
% - swe_{unit}_{T|F}stat_lpFWE-WB_c{c#}:
% Log10 map of the voxelwise bootstrap-calculated FWE P values for
% contrast {c#}.
%
% - swe_{unit}_{T|F}stat_lpFDR-WB_c{c#}:
% Log10 map of the voxelwise bootstrap-calculated FDR P values for
% contrast {c#}.
%
% - swe_clustere_{T|F}stat_lpFWE-WB_c{c#}:
% Log10 map of the clusterwise bootstrap-calculated FWE P values
% for contrast {c#}.
%
% - swe_tfce_c{c#}:
% TFCE parametric statistic map for contrast {c#}.
%
% - swe_tfce_lp-WB_c{c#}:
% Log10 map of the TFCE bootstrap-calculated P values for contrast
% {c#}.
%
% - swe_tfce_lpFWE-WB_c{c#}:
% Log10 map of the TFCE bootstrap-calculated FWE P values for
% contrast {c#}.
%
% The field {unit} used above represents the unit in space in which the statistic is calculated.
% It can be the following strings:
% - 'vox' for NifTI files,
% - 'dpx' for GIfTI and CIfTI files,
% - 'dat' for .mat files.
% Currently (30/08/2018), the only contrasts computed are activation
% (contrast #1) and deactivation (contrast #2) for the contrast vector the
% user input during the batch entry.
% =========================================================================
% FORMAT swe_cp_WB(SwE)
% -------------------------------------------------------------------------
% Inputs:
% - SwE: SwE data structure
% =========================================================================
% Version Info: $Format:%ci$ $Format:%h$
%-Say hello
%--------------------------------------------------------------------------
Finter = spm('CreateIntWin','off');
set(Finter,'name','SwE estimation');
set(Finter,'vis','on')
%-Change to SwE.swd if specified
%--------------------------------------------------------------------------
try
cd(SwE.swd);
catch %#ok<*CTCH>
SwE.swd = pwd;
end
%-Shuffle seed of random number generator
%--------------------------------------------------------------------------
swe_seed
%-Ensure data are assigned
%--------------------------------------------------------------------------
try
SwE.xY.VY;
catch
spm('alert!','Please assign data to this design', mfilename);
spm('FigName','Stats: done',Finter); spm('Pointer','Arrow')
return
end
%-Check if we have data in a.mat format and set some variables accordingly
%--------------------------------------------------------------------------
file_ext = swe_get_file_extension(SwE.xY.P{1});
isMat = strcmpi(file_ext,'.mat');
isCifti = strcmpi(file_ext,'.dtseries.nii') || strcmpi(file_ext,'.dscalar.nii');
isOctave = exist('OCTAVE_VERSION','builtin');
if isCifti
metadata = {'ciftiTemplate', SwE.xY.P{1}};
file_data_type = 'dpx';
dataType = swe_DataType('Cifti');
dataTypeSpecificInformation = SwE.cifti;
end
if isMat
file_data_type = 'dat';
if SwE.WB.clusterWise == 1
isVolumeMat = isfield(SwE.WB.clusterInfo, 'Vxyz');
isSurfaceMat = isfield(SwE.WB.clusterInfo, 'Vfaces');
if isVolumeMat
dataType = swe_DataType('VolumeMat');
dataTypeSpecificInformation = [];
elseif isSurfaceMat
dataType = swe_DataType('SurfaceMat');
dataTypeSpecificInformation = importdata(SwE.WB.clusterInfo.Vfaces{1});
if size(dataTypeSpecificInformation,1) ~=3 && size(dataTypeSpecificInformation,2) ~=3
error('faces coodinates do not seem correct')
elseif size(dataTypeSpecificInformation,1) == 3
dataTypeSpecificInformation = dataTypeSpecificInformation';
end
else
dataType = swe_DataType('Mat');
dataTypeSpecificInformation = [];
end
else
dataType = swe_DataType('Mat');
dataTypeSpecificInformation = [];
end
end
if ~isMat && ~isCifti
isMeshData = spm_mesh_detect(SwE.xY.VY);
if isMeshData
file_ext = '.gii';
file_data_type = 'dpx';
dataType = swe_DataType('Gifti');
g = SwE.xY.VY(1).private;
metadata = g.private.metadata;
name = {metadata.name};
if any(ismember(name,'SurfaceID'))
metadata = metadata(ismember(name,'SurfaceID'));
metadata = {metadata.name, metadata.value};
elseif isfield(g,'faces') && ~isempty(g.faces)
metadata = {'SurfaceID', SwE.xY.VY(1).fname};
else
error('SurfaceID not found in GIfTI''s metadata.');
end
if isempty(spm_file(metadata{2},'path'))
metadata{2} = fullfile(spm_file(SwE.xY.VY(1).fname,'path'),metadata{2});
end
SwE.xVol.G = metadata{2};
if (SwE.WB.clusterWise == 1)
dataTypeSpecificInformation = export(gifti(SwE.xVol.G),'patch');
end
else
dataType = swe_DataType('Nifti');
dataTypeSpecificInformation = [];
file_ext = spm_file_ext;
file_data_type = 'vox';
metadata = {};
end
else
isMeshData = false;
end
try
giftiAreaFile = SwE.gifti.areaFile;
catch
giftiAreaFile = '';
end
isVolumeMat = (dataType == swe_DataType('VolumeMat'));
isSurfaceMat = (dataType == swe_DataType('SurfaceMat'));
isNifti = (dataType == swe_DataType('Nifti'));
isGifti = (dataType == swe_DataType('Gifti'));
%-Check whether we are doing a TFCE analysis
%--------------------------------------------------------------------------
% deactivate for now TFCE if we analyse surface data
TFCE = isfield(SwE.WB, 'TFCE') && ~isMeshData;
if TFCE
H = SwE.WB.TFCE.H;
E = SwE.WB.TFCE.E;
dh = SwE.WB.TFCE.dh;
C = 18;
end
%-Prevent unnecessary octave warning
%--------------------------------------------------------------------------
if isOctave
warning ('off', 'histc: empty EDGES specified\n');
end
%-Delete files from previous analyses
%--------------------------------------------------------------------------
if exist(fullfile(SwE.swd,sprintf('swe_v%s_mask%s',file_data_type,file_ext)),'file') == 2
str = {'Current directory contains SwE estimation files:',...
'pwd = ',SwE.swd,...
'Existing results will be overwritten!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1)
spm('FigName','Stats: done',Finter); spm('Pointer','Arrow')
return
else
warning('Overwriting old results\n\t (pwd = %s) ',SwE.swd); %#ok<WNTAG>
end
end
files = {'^swe_.{3}_mask(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_cov_b\d{2}_b\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_cov_vv(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_cov(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_con_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_beta_b\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_cov_g\d{2}_v\d{2}_v\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_cov_g\d{2}_b\d{2}_b\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_edf_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_beta_\w{1}\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_\w{1,2}stat_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_\w{1,2}stat-WB_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_\w{1,2}stat_lp\w{0,3}_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_\w{1,2}stat_lp\w{0,3}-WB_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_clustere_\w{1,2}stat_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_clustere_\w{1,2}stat_lp\w{0,3}-WB_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_clusternorm\d{0,1}_\w{1,2}stat_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_clusternorm\d{0,1}_\w{1,2}stat_lp\w{0,3}-WB_c\d{2}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_resid_y\d{2,4}(\.dtseries)?(\.dscalar)?\..{3}$',...
'^swe_.{3}_fit_y\d{2,4}(\.dtseries)?(\.dscalar)?\..{3}$'};
for i = 1:length(files)
j = spm_select('List',SwE.swd,files{i});
for k = 1:size(j,1)
spm_unlink(deblank(j(k,:)));
end
end
% Tolerance for comparing real numbers
tol = 1e-8;
%==========================================================================
% - A N A L Y S I S P R E L I M I N A R I E S
%==========================================================================
%-Initialise
%==========================================================================
fprintf('%-40s: %30s','Initialising parameters','...computing'); %-#
xX = SwE.xX;
[nScan, nBeta] = size(xX.X);
nCov_beta = (nBeta+1)*nBeta/2;
pX = pinv(xX.X); % pseudo-inverse
iSubj = SwE.Subj.iSubj;
uSubj = unique(iSubj);
nSubj = length(uSubj);
SwE.Subj.uSubj = uSubj;
SwE.Subj.nSubj = nSubj;
%-WB variables
%
WB = SwE.WB;
conWB = WB.con;
nSizeCon = size(conWB,1);
rankCon = rank(conWB);
% If clusterWise inference, force the U-SwE to be used
if WB.clusterWise == 1 && WB.RSwE ==1
WB.RSwE = 0;
SwE.WB.RSwE = 0;
if isOctave
save('SwE.mat','SwE');
elseif spm_check_version('matlab','7') >=0
save('SwE','SwE','-V6');
else
save('SwE','SwE');
end
end
% If clusterWise inference and .mat format, check for the presence of
% spatial information
if isMat && WB.clusterWise == 1
if isVolumeMat
XYZ = importdata(SwE.WB.clusterInfo.Vxyz{1});
if size(XYZ,1) ~=3 && size(XYZ,2) ~=3
error('voxel coodinates do not seem correct')
elseif size(XYZ,2) ==3
XYZ = XYZ';
end
elseif ~isSurfaceMat
error('clusterWise inference cannot be done without spatial information when inputs are in ".mat" format. Please supply faces coordinates (faces or tris) for surface data or voxel coordinates (XYZ_vox) for volumetric data');
end
end
% small sample correction (for WB)
[corrWB, tmpR2] = swe_resid_corr(SwE, 1, WB.SS, pX);
% small sample correction (for parametric)
[corr, tmpR2] = swe_resid_corr(SwE, WB.RSwE, SwE.SS, pX, tmpR2);
%-detect if the design matrix is separable (a little bit messy, but seems to do the job)
%
iGr_dof = zeros(1,nScan);
iBeta_dof = zeros(1,nBeta);
it = 0;
while ~all(iGr_dof)
it = it + 1;
scan = find(iGr_dof==0,1);
if any(xX.X(scan,:)) % handle the case where a row is all 0s (BG - 05/08/2016; Thanks to Ged Ridgway for finding the bug)
for i = find(iGr_dof==0)
if any((xX.X(i,:) & xX.X(scan,:)))
iGr_dof(i) = it;
end
end
else
iGr_dof(scan) = it;
end
end
%need to check if the partition is correct
while 1
uGr_dof = unique(iGr_dof);
nGr_dof = length(uGr_dof);
tmp = zeros(nGr_dof,nBeta);
for i = 1:nGr_dof
tmp(i,:) = any(xX.X(iGr_dof==uGr_dof(i),:));
end
if nGr_dof==1 | all(sum(tmp, 1)==1) %#ok<OR2>
break % all is ok, just stop the while
else
ind1 = find(sum(tmp, 1)>1,1); % detect the first column in common
ind2 = find(tmp(:,ind1)==1); % detect the groups to be fused
for ii = ind2'
iGr_dof(iGr_dof==uGr_dof(ii)) = ind2(1); % fuse the groups
end
end
end
nSubj_dof = zeros(1,nGr_dof);
for i = 1:nGr_dof % renumber to avoid gaps in the numbering
iGr_dof(iGr_dof==uGr_dof(i)) = i;
iBeta_dof(tmp(i,:)==1) = i;
nSubj_dof(i) = length(unique(iSubj(iGr_dof==uGr_dof(i))));
end
pB_dof = zeros(1,nGr_dof);
for i=1:nBeta
tmp=1;
for ii=1:nSubj
if length(unique(xX.X(iSubj==uSubj(ii)&iGr_dof'==iBeta_dof(i),i)))>1
tmp=0;
break
end
end
if tmp == 1
pB_dof(iBeta_dof(i)) = pB_dof(iBeta_dof(i)) + 1;
end
end
%-effective dof for each subject
edof_Subj = zeros(1,nSubj);
for i = 1:nSubj
edof_Subj(i) = 1 - pB_dof(iGr_dof(iSubj==uSubj(i)))/...
nSubj_dof(iGr_dof(iSubj==uSubj(i)));
end
%-degrees of freedom estimation type
if isfield(SwE.type,'modified')
dof_type = SwE.type.modified.dof_mo;
else
dof_type = SwE.type.classic.dof_cl;
end
if dof_type == 0 % so naive estimation is used
if nSizeCon==1
ind = find(conWB ~= 0);
else
ind = find(any(conWB~=0));
end
indSubDesignMatrices = iBeta_dof(ind);
subjectsInvolved = [];
for iIndSubDesignMatrices = indSubDesignMatrices
subjectsInvolved = [subjectsInvolved; iSubj(iGr_dof == iIndSubDesignMatrices)];
end
subjectsInvolved = unique(subjectsInvolved);
indSubjInvolved = nan(length(subjectsInvolved),1);
% convert into in
for iSubjInvolved = 1:length(subjectsInvolved)
indSubjInvolved(iSubjInvolved) = find(uSubj == subjectsInvolved(iSubjInvolved));
end
edf = sum(edof_Subj(indSubjInvolved));
dof_cov = zeros(1,nBeta);
for i = 1:nBeta
dof_cov(i) = nSubj_dof(iBeta_dof(i)) - ...
pB_dof(iBeta_dof(i));
end
% This variable should be left empty for Niave estimation.
dofMat = [];
xX.erdf_niave = edf;
SwE.xX = xX;
else
edf = NaN;
end
%-preprocessing for the modified SwE
if isfield(SwE.type,'modified')
if dof_type == 1
error('degrees of freedom type still not implemented for the modified SwE and the WB')
end
iVis = SwE.Vis.iVis;
iGr = SwE.Gr.iGr;
uGr = unique(iGr);
nGr = length(uGr);
SwE.Gr.uGr = uGr;
SwE.Gr.nGr = nGr;
% info specific for each group
uVis_g = cell(1,nGr); % unique visits for each group
nVis_g = zeros(1,nGr); % number of visits for each group
uSubj_g = cell(1,nGr); % unique visits for each group
nSubj_g = zeros(1,nGr); % number of visits for each group
for g = 1:nGr
uVis_g{g} = unique(iVis(iGr==uGr(g)));
nVis_g(g) = length(uVis_g{g});
iSubj_g = iSubj(iGr==uGr(g)); % Subject number for each subject in group for each visit
uSubj_g{g} = unique(iSubj_g); % Unique subject numbers of subjects in group
nSubj_g(g) = length(uSubj_g{g});
uSubj_g_tmp = uSubj_g{g};
for k = 1:nSubj_g(g)
% The number of visits for subject uSubj_g(k)
vis_g_subj(k) = sum(iSubj_g==uSubj_g_tmp(k));
end
max_nVis_g(g) = max(vis_g_subj);
min_nVis_g(g) = min(vis_g_subj);
clear vis_g_subj
end
nCov_vis_g = nVis_g.*(nVis_g+1)/2; % number of covariance elements to be estimated for each group
nCov_vis = sum(nCov_vis_g); % total number of covariance elements to be estimated
% Save Vis variables.
SwE.Vis.uVis_g = uVis_g;
SwE.Vis.nVis_g = nVis_g;
SwE.Vis.max_nVis_g = max_nVis_g;
SwE.Vis.min_nVis_g = min_nVis_g;
% Flags matrices indicating which residuals have to be used for each covariance element
Flagk = false(nCov_vis,nScan); % Flag indicating scans corresponding to visit k for each covariance element
Flagkk = false(nCov_vis,nScan); % Flag indicating scans corresponding to visit kk for each covariance element
Ind_Cov_vis_diag = nan(1,sum(nVis_g)); % index of the diagonal elements
Ind_Cov_vis_off_diag = nan(1,nCov_vis - sum(nVis_g)); % index of the off-diagonal elements
Ind_corr_diag=nan(nCov_vis,2); % index of the 2 corresponding diagonal elements
iGr_Cov_vis_g = nan(1,nCov_vis);
it = 0; it2 = 0; it3 = 0;
for g = 1:nGr
for k = 1:nVis_g(g)
for kk = k:nVis_g(g)
it = it + 1;
id = intersect(iSubj(iGr==uGr(g) & iVis==uVis_g{g}(k)),...
iSubj(iGr==uGr(g) & iVis==uVis_g{g}(kk))); % identifiaction of the subjects with both visits k & kk
Flagk(it,:) = ismember(iSubj,id) & iVis==uVis_g{g}(k);
Flagkk(it,:) = ismember(iSubj,id) & iVis==uVis_g{g}(kk);
if k==kk
it2 = it2+1;
it4 = it2;
Ind_Cov_vis_diag(it2) = it;
else
it3 = it3 + 1;
it4 = it4 + 1;
Ind_Cov_vis_off_diag(it3) = it;
end
Ind_corr_diag(it,:) = [it2 it4];
iGr_Cov_vis_g(it) = g;
end
end
end
% Record igr_Cov_vis_g.
SwE.WB.iGr_Cov_vis_g = iGr_Cov_vis_g;
% weights for the vectorised SwE
weight = NaN(nCov_beta,nCov_vis);
it=0;
for j = 1:nBeta
for jj = j:nBeta
it=it+1;
for jjj = Ind_Cov_vis_diag
weight(it,jjj) = pX(j,Flagk(jjj,:))*pX(jj,Flagk(jjj,:))';
end
for jjj = Ind_Cov_vis_off_diag
weight(it,jjj) = pX(j,Flagk(jjj,:))*pX(jj,Flagkk(jjj,:))' + ...
pX(j,Flagkk(jjj,:))*pX(jj,Flagk(jjj,:))';
end
end
end
% Weight giving only the contrasted SwE (WB)
weightR = pinv(swe_duplication_matrix(nSizeCon)) * kron(conWB,conWB) * swe_duplication_matrix(nBeta) * weight; % used to compute the R SwE R'
Wg = cell(nGr,1);
Wg_testII = cell(nGr,1);
Wg_testIII = cell(nGr,1);
tmp = eye(nSizeCon^2);
for g = 1:nGr
Wg{g} = kron(weightR(:,iGr_Cov_vis_g==g),weightR(:,iGr_Cov_vis_g==g)) * swe_duplication_matrix(nCov_vis_g(g));
Wg_testII{g} = sum(kron(swe_duplication_matrix(nSizeCon),swe_duplication_matrix(nSizeCon)), 1) * Wg{g};
Wg_testIII{g} = tmp(:)' * (kron(swe_duplication_matrix(nSizeCon),swe_duplication_matrix(nSizeCon))) * Wg{g};
end
SwE.WB.Wg{1} = Wg;
SwE.WB.Wg{2} = Wg_testII;
SwE.WB.Wg{3} = Wg_testIII;
%-compute the effective dof from each homogeneous group if dof_type
switch dof_type
case 1
dofMat = NaN;
edof_Gr = zeros(1,nGr);
nSubj_g = zeros(1,nGr);
for g = 1:nGr
nSubj_g(g) = length(unique(iSubj(iGr == g)));
tmp = 0;
for j = 1:nSubj_g(g)
tmp = tmp + 1/edof_Subj(uSubj == uSubj_g{g}(j));
end
edof_Gr(g) = nSubj_g(g)^2/tmp;
end
case {2,3} % compute a matrix containing the variables linked to the degrees of freedom (for test II and III)
dofMat = cell(nGr,1);
for g = 1:nGr
dofMat{g} = zeros(nCov_vis_g(g));
it1 =0;
for i = 1:nVis_g(g)
for j = i:nVis_g(g)
it1 = it1 + 1;
it2 = 0;
for a = 1:nVis_g(g)
for b = a:nVis_g(g)
it2 = it2 + 1;
mij = 0;mab = 0;tmp = 0;
for ii = 1:nSubj_g(g)
mij = mij + 1*(...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(i)) &...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(j)));
mab = mab + 1*(...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(a)) &...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(b)));
tmp = tmp + 1*(...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(a)) &...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(b)) &...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(i)) &...
any(iSubj==uSubj_g{g}(ii) & iVis==uVis_g{g}(j)))...
/edof_Subj(uSubj==uSubj_g{g}(ii));
end
dofMat{g}(it1,it2) = tmp/mij/mab;
end
end
end
end
dofMat{g}(isnan(dofMat{g})) = 0;
end
clear tmp mij mab
end
end
%-preprocessing for the classic SwE
if isfield(SwE.type,'classic')
nVis_i = zeros(1,nSubj);
for i = 1:nSubj
nVis_i(i) = sum(uSubj(i)==iSubj);
end
nCov_vis = sum(nVis_i.*(nVis_i+1)/2); % total number of covariance elements to be estimated
weight = NaN(nCov_beta,nCov_vis);
Ind_Cov_vis_classic = NaN(1,nCov_vis);
Indexk = NaN(1,nCov_vis);
Indexkk = NaN(1,nCov_vis);
it=0;
for j = 1:nBeta
for jj = j:nBeta
it = it + 1;
it2 = 0;
for i = 1:nSubj
ind_i=find(iSubj == uSubj(i));
for ii = 1:nVis_i(i)
it2 = it2 + 1;
weight(it,it2) = pX(j,ind_i(ii))*pX(jj,ind_i(ii));
Ind_Cov_vis_classic(it2) = i;
Indexk(it2) = ind_i(ii);
Indexkk(it2) = ind_i(ii);
for iii = (ii+1):nVis_i(i)
it2 = it2 + 1;
weight(it,it2) = pX(j,ind_i([ii,iii]))*pX(jj,ind_i([iii,ii]))';
Ind_Cov_vis_classic(it2) = i;
Indexk(it2) = ind_i(ii);
Indexkk(it2) = ind_i(iii);
end
end
end
end
end
%-compute the effective dof from each homogeneous group (here, subject)
if dof_type == 1
edof_Gr = edof_Subj;
end
weightR = pinv(swe_duplication_matrix(nSizeCon)) * kron(conWB,conWB) * swe_duplication_matrix(nBeta) * weight; % used to compute the R SwE R'
end
%-If xM is not a structure then assume it's a vector of thresholds
%--------------------------------------------------------------------------
try
xM = SwE.xM;
catch
xM = -Inf(nScan,1);
end
if ~isstruct(xM)
xM = struct('T', [],...
'TH', xM,...
'I', 0,...
'VM', {[]},...
'xs', struct('Masking','analysis threshold'));
end
fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...done'); %-#
if ~isMat
%-Image dimensions and data
%==========================================================================
VY = SwE.xY.VY;
spm_check_orientations(VY);
% check files exists and try pwd
%--------------------------------------------------------------------------
for i = 1:numel(VY)
if ~spm_existfile(VY(i).fname)
[p,n,e] = fileparts(VY(i).fname);
VY(i).fname = [n,e];
end
end
M = VY(1).mat;
DIM = VY(1).dim;
YNaNrep = VY(1).dt(2);
fprintf('%-40s: %30s','Output images','...initialising'); %-#
%-Initialise new mask name: current mask & conditions on voxels
%----------------------------------------------------------------------
VM = swe_data_hdr_write(sprintf('swe_%s_mask%s', file_data_type, file_ext), DIM, M,...
'swe_cp:resultant analysis mask', metadata, 'uint8');
%-Initialise beta image files
%----------------------------------------------------------------------
for i = 1:nBeta
Vbeta(i) = swe_data_hdr_write(sprintf('swe_%s_beta_b%02d%s',file_data_type,i,file_ext),...
DIM, M,...
sprintf('swe_cp:beta (%02d) - %s',i,xX.name{i}),...
metadata);
end
%-Initialise original parametric score image, T or F
%----------------------------------------------------------------------
if WB.stat=='T'
eSTAT='z';
else % F stat
eSTAT='x';
end
Vscore = swe_data_hdr_write(sprintf('swe_%s_%cstat_c%02d%s', file_data_type, WB.stat, 1, file_ext), DIM, M,...
sprintf('Original parametric %c statistic data.', WB.stat), metadata);
%-Initialise parametric TFCE score image, if TFCE has been selected.
%----------------------------------------------------------------------
if TFCE
Vscore_tfce = swe_data_hdr_write(sprintf('swe_tfce_c%02d%s', 1, file_ext), DIM, M,...
'Original parametric TFCE statistic data.', metadata);
if WB.stat=='T'
Vscore_tfce_neg = swe_data_hdr_write(sprintf('swe_tfce_c%02d%s', 2, file_ext), DIM, M,...
'Original parametric TFCE statistic data for a negative contrast.', metadata);
end
end
%-Initialise original parametric edf image
%----------------------------------------------------------------------
Vedf = swe_data_hdr_write(sprintf('swe_%s_edf_c%02d%s', file_data_type, 1, file_ext), DIM, M,...
sprintf('Original parametric %c edf data.', WB.stat), metadata);
%-Initialise parametric P-Value image
%----------------------------------------------------------------------
VlP = swe_data_hdr_write(sprintf('swe_%s_%cstat_lp_c%02d%s', file_data_type, WB.stat, 1, file_ext), DIM, M,...
'Original parametric -log10(P) value data (positive).', metadata);
if WB.stat=='T'
VlP_Neg = swe_data_hdr_write(sprintf('swe_%s_%cstat_lp_c%02d%s', file_data_type, WB.stat, 2, file_ext), DIM, M,...
'Original parametric -log10(P) value data (negative).', metadata);
end
%-Initialise converted parametric score image
%----------------------------------------------------------------------
VcScore = swe_data_hdr_write(sprintf('swe_%s_%c%cstat_c%02d%s', file_data_type, eSTAT, WB.stat, 1, file_ext), DIM, M,...
sprintf('Parametric %c statistic data derived from %c-Statistic data.', eSTAT, WB.stat), metadata);
if WB.stat=='T'
VcScore_neg = swe_data_hdr_write(sprintf('swe_%s_%c%cstat_c%02d%s', file_data_type, eSTAT, WB.stat, 2, file_ext), DIM, M,...
sprintf('Parametric %c statistic data derived from %c-Statistic data.', eSTAT, WB.stat), metadata);
end
%-Initialise residual images for the resampling
%----------------------------------------------------------------------
for i = 1:nScan
descrip = sprintf('adjusted restricted residuals (%04d)', i);
VResWB(i) = swe_data_hdr_write(sprintf('swe_%s_resid_y%04d%s', file_data_type, i, file_ext), DIM, M, descrip, metadata);
end
%-Initialise fitted data images for the resampling
%----------------------------------------------------------------------
for i = 1:nScan
descrip = sprintf('restricted fitted data (%04d)', i);
VYWB(i) = swe_data_hdr_write(sprintf('swe_%s_fit_y%04d%s',file_data_type,i,file_ext), DIM, M, descrip, metadata);
end
%-Initialise result images
%----------------------------------------------------------------------
VlP_wb_pos = swe_data_hdr_write(sprintf('swe_%s_%cstat_lp-WB_c%02d%s', file_data_type, WB.stat, 1, file_ext), DIM, M,...
'Non-parametric voxelwise -log10(P) value data (positive).', metadata);
VlP_wb_FWE_pos = swe_data_hdr_write(sprintf('swe_%s_%cstat_lpFWE-WB_c%02d%s', file_data_type, WB.stat, 1, file_ext), DIM, M,...
'Non-parametric voxelwise FWE -log10(P) value data (positive).', metadata);
VlP_wb_FDR_pos = swe_data_hdr_write(sprintf('swe_%s_%cstat_lpFDR-WB_c%02d%s', file_data_type, WB.stat, 1, file_ext), DIM, M,...
'Non-parametric voxelwise FDR -log10(P) value data (positive).', metadata);
if WB.stat=='T'
VlP_wb_neg = swe_data_hdr_write(sprintf('swe_%s_%cstat_lp-WB_c%02d%s', file_data_type, WB.stat, 2, file_ext), DIM, M,...
'Non-parametric voxelwise -log10(P) value data (negative).', metadata);
VlP_wb_FWE_neg = swe_data_hdr_write(sprintf('swe_%s_%cstat_lpFWE-WB_c%02d%s', file_data_type, WB.stat, 2, file_ext), DIM, M,...
'Non-parametric voxelwise FWE -log10(P) value data (negative).', metadata);
VlP_wb_FDR_neg = swe_data_hdr_write(sprintf('swe_%s_%cstat_lpFDR-WB_c%02d%s', file_data_type, WB.stat, 2, file_ext), DIM, M,...
'Non-parametric voxelwise FDR -log10(P) value data (negative).', metadata);
end
%-Initialise parametric TFCE results images, if TFCE has been selected.
%----------------------------------------------------------------------
if TFCE
VlP_tfce_pos = swe_data_hdr_write(sprintf('swe_tfce_lp-WB_c%02d%s', 1, file_ext), DIM, M,...
'Non-parametric TFCE -log10(P) value data (positive).', metadata);
VlP_tfce_FWE_pos = swe_data_hdr_write(sprintf('swe_tfce_lpFWE-WB_c%02d%s', 1, file_ext), DIM, M,...
'Non-parametric TFCE FWE -log10(P) value data (positive).', metadata);
if WB.stat=='T'
VlP_tfce_neg = swe_data_hdr_write(sprintf('swe_tfce_lp-WB_c%02d%s', 2, file_ext), DIM, M,...
'Non-parametric TFCE -log10(P) value data (negative).', metadata);
VlP_tfce_FWE_neg = swe_data_hdr_write(sprintf('swe_tfce_lpFWE-WB_c%02d%s', 2, file_ext), DIM, M,...
'Non-parametric TFCE FWE -log10(P) value data (negative).', metadata);
end
end
% Converted score for WB.
VcScore_wb_pos = swe_data_hdr_write(sprintf('swe_%s_%c%cstat-WB_c%02d%s', file_data_type, eSTAT, WB.stat, 1, file_ext), DIM, M,...
sprintf('Non-parametric %c statistic data derived from %c-Statistic data.', eSTAT, WB.stat), metadata);
if WB.clusterWise == 1
% We also need cluster p value maps here.
V_clustere_pos = swe_data_hdr_write(sprintf('swe_clustere_%cstat_c%02d%s', WB.stat, 1, file_ext), DIM, M,...
sprintf('Cluster extent (positive, CFT %g).',...
SwE.WB.clusterInfo.primaryThreshold), metadata);
if WB.stat=='T'
V_clustere_neg = swe_data_hdr_write(sprintf('swe_clustere_%cstat_c%02d%s', WB.stat, 2, file_ext), DIM, M,...
sprintf('Cluster extent (negative, CFT %g).',...
SwE.WB.clusterInfo.primaryThreshold), metadata);
end
end
fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...initialised'); %-#
%==========================================================================
% - F I T M O D E L & W R I T E P A R A M E T E R I M A G E S
%==========================================================================
%-Get explicit mask(s)
%==========================================================================
mask = true(DIM);
nDataElements = numel(mask);
for i = 1:numel(xM.VM)
if isCifti
v = swe_data_read(xM.VM(i)) > 0;
mask = mask & v(:);
clear v
elseif ~(isfield(SwE,'xVol') && isfield(SwE.xVol,'G'))
%-Assume it fits entirely in memory
coeff = spm_bsplinc(xM.VM(i), [0 0 0 0 0 0]');
v = true(DIM);
[x1,x2] = ndgrid(1:DIM(1),1:DIM(2));
for x3 = 1:DIM(3)
M2 = inv(M\xM.VM(i).mat);
y1 = M2(1,1)*x1+M2(1,2)*x2+(M2(1,3)*x3+M2(1,4));
y2 = M2(2,1)*x1+M2(2,2)*x2+(M2(2,3)*x3+M2(2,4));
y3 = M2(3,1)*x1+M2(3,2)*x2+(M2(3,3)*x3+M2(3,4));
v(:,:,x3) = spm_bsplins(coeff, y1,y2,y3, [0 0 0 0 0 0]') > 0;
end
mask = mask & v;
clear coeff v x1 x2 x3 M2 y1 y2 y3
else
if spm_mesh_detect(xM.VM(i))
v = xM.VM(i).private.cdata() > 0;
else
v = spm_mesh_project(gifti(SwE.xVol.G), xM.VM(i)) > 0;
end
mask = mask & v(:);
clear v
end
end
%-Split data into chunks
%==========================================================================
chunksize = floor(spm_get_defaults('stats.maxmem') / 8 / nScan);
nbchunks = ceil(prod(DIM) / chunksize);
chunks = min(cumsum([1 repmat(chunksize,1,nbchunks)]),prod(DIM)+1);
% activated voxels for cluster-wise inference
if (WB.clusterWise == 1)
activatedVoxels = false(0);
maxClusterSize = nan(1, WB.nB + 1);
maxClusterSizeInSurfaces = nan(1, WB.nB + 1);
maxClusterSizeInVolume = nan(1, WB.nB + 1);
activatedVoxelsNeg = false(0);
if (WB.stat == 'T')
maxClusterSizeNeg = nan(1, WB.nB + 1);
maxClusterSizeInSurfacesNeg = nan(1, WB.nB + 1);
maxClusterSizeInVolumeNeg = nan(1, WB.nB + 1);
end
end
maxScore = nan(1, WB.nB + 1);
if (WB.stat == 'T')
minScore = nan(1, WB.nB + 1);
end
%-Cycle over bunches blocks within planes to avoid memory problems
%==========================================================================
swe_progress_bar('Init',nbchunks,'Parameter estimation','Chunks');
for iChunk=1:nbchunks
chunk = chunks(iChunk):chunks(iChunk+1)-1;
%-Report progress
%======================================================================
if iChunk > 1, fprintf(repmat(sprintf('\b'),1,72)); end %-#
fprintf('%-40s: %30s', sprintf('Original statistics: Chunk %3d/%-3d',iChunk,nbchunks),...
'...processing');
%-Get the data in mask, compute threshold & implicit masks
%------------------------------------------------------------------
Y = zeros(nScan, numel(chunk));
cmask = mask(chunk);
if size(cmask, 2) == 1
cmask = cmask';
end
for iScan=1:nScan
if ~any(cmask), break, end %-Break if empty mask
Y(iScan, cmask) = swe_data_read(VY(iScan), chunk(cmask));%-Read chunk of data
cmask(cmask) = Y(iScan, cmask) > xM.TH(iScan); %-Threshold (& NaN) mask
if xM.I && ~YNaNrep && xM.TH(iScan) < 0 %-Use implicit mask
cmask(cmask) = abs(Y(iScan, cmask)) > eps;
end
end
cmask(cmask) = any(diff(Y(:,cmask),1));
%-Mask out voxels where data is constant in at least one separable
% matrix design either in a visit category or within-subject (BG - 27/05/2016)
%------------------------------------------------------------------
[cmask, Y, CrS] = swe_mask_seperable(SwE, cmask, Y, iGr_dof);
%==================================================================
%-Proceed with General Linear Model (if there are voxels)
%==================================================================
if CrS
%-General linear model: Ordinary least squares estimation
%--------------------------------------------------------------
beta = pX*Y; %-Parameter estimates
% restricted fitted data
[resWB, YWB] = swe_fit(SwE, Y, tmpR2, corrWB, beta, SwE.WB.SS);
if WB.RSwE == 1
res = swe_fit(SwE, Y, tmpR2, corr, beta, SwE.SS);
else
res = swe_fit(SwE, Y, xX.X, corr, beta, SwE.SS);
end
clear Y %-Clear to save memory
%-Estimation of the data variance-covariance components (modified SwE)
%-SwE estimation (classic version)
%--------------------------------------------------------------
if isfield(SwE.type,'modified')
Cov_vis=zeros(nCov_vis,CrS);
for i = Ind_Cov_vis_diag
Cov_vis(i,:) = mean(res(Flagk(i,:),:).^2, 1);
end
% Check if some voxels have variance < eps and mask them
tmp = ~any(Cov_vis(Ind_Cov_vis_diag,:) < eps); % modified by BG on 29/08/16
if any(~tmp)
beta = beta(:,tmp);
resWB = resWB(:,tmp);
res = res(:,tmp);
YWB = YWB(:,tmp);
cmask(cmask) = tmp;
CrS = sum(cmask);
Cov_vis = Cov_vis(:,tmp);
end
if CrS % Check if there is at least one voxel left
% compute the visit covariance matrices
for i = Ind_Cov_vis_off_diag
if any(Flagk(i,:))
Cov_vis(i,:)= sum(res(Flagk(i,:),:).*res(Flagkk(i,:),:), 1).*...
sqrt(Cov_vis(Ind_Cov_vis_diag(Ind_corr_diag(i,1)),:).*...
Cov_vis(Ind_Cov_vis_diag(Ind_corr_diag(i,2)),:)./...
sum(res(Flagk(i,:),:).^2, 1)./...
sum(res(Flagkk(i,:),:).^2, 1));
end
end
%NaN may be produced in cov. estimation when one correspondant
%variance are = 0, so set them to 0
Cov_vis(isnan(Cov_vis))=0;
%need to check if the eigenvalues of Cov_vis matrices are >=0
if dof_type == 1
tmpSum = zeros(1,CrS);
end
for g = 1:nGr
for iVox = 1:CrS
tmp = zeros(nVis_g(g));
tmp(tril(ones(nVis_g(g)))==1) = Cov_vis(iGr_Cov_vis_g==g,iVox);
tmp = tmp + tmp' - diag(diag(tmp));
[V D] = eig(tmp);
if any (diag(D)<0) %Bug corrected (BG - 19/09/13)
D(D<0) = 0;
tmp = V * D * V';
Cov_vis(iGr_Cov_vis_g==g,iVox) = tmp(tril(ones(nVis_g(g)))==1); %Bug corrected (BG - 19/09/13)
end
if dof_type == 1
Cov_beta_g_tmp = weightR(:, iGr_Cov_vis_g==g) * Cov_vis(iGr_Cov_vis_g==g,:);
if nSizeCon == 1
tmpSum = tmpSum + Cov_beta_g_tmp.^2/edof_Gr(g);
else
for iVox = 1:CrS
cCovBc_g_vox = zeros(nSizeCon);
cCovBc_g_vox(tril(ones(nSizeCon))==1) = Cov_beta_g_tmp(:, iVox);
cCovBc_g_vox = cCovBc_g_vox + cCovBc_g_vox' - diag(diag(cCovBc_g_vox));
tmpSum(iVox) = tmpSum(iVox) + (trace(cCovBc_g_vox^2) + (trace(cCovBc_g_vox))^2)/edof_Gr(g);
end
end
end
end
end
end
cCovBc = weightR * Cov_vis;
clear Cov_beta_g_tmp
else % else for "if isfield(SwE.type,'modified')"
cCovBc = 0;
if dof_type == 1
tmpSum = zeros(1,CrS);
end
for i = 1:nSubj
Cov_beta_i_tmp = weightR(:,Ind_Cov_vis_classic==i) *...
(res(Indexk(Ind_Cov_vis_classic==i),:) .* res(Indexkk(Ind_Cov_vis_classic==i),:));
cCovBc = cCovBc + Cov_beta_i_tmp;
if dof_type == 1
if nSizeCon == 1
tmpSum = tmpSum + Cov_beta_i_tmp.^2/edof_Gr(i);
else
for iVox = 1:CrS
cCovBc_g_vox = zeros(nSizeCon);
cCovBc_g_vox(tril(ones(nSizeCon))==1) = Cov_beta_i_tmp(:,iVox);
cCovBc_g_vox = cCovBc_g_vox + cCovBc_g_vox' - diag(diag(cCovBc_g_vox));
tmpSum(iVox) = tmpSum(iVox) + (trace(cCovBc_g_vox^2) + (trace(cCovBc_g_vox))^2)/edof_Gr(i);
end
end
end
end
% These variables are left empty for classic SwE.
Cov_vis = [];
dofMat = [];