-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathspm_superres_lib.m
1408 lines (1228 loc) · 42.2 KB
/
spm_superres_lib.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 varargout = spm_superres_lib(varargin)
%__________________________________________________________________________
% Library of functions for spm_superres.
%
% FORMAT out = spm_superres_lib('name'in)
%
% FORMAT help spm_superres_lib>function
% Returns the help file of the selected function.
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
if nargin == 0
help spm_superres_lib
error('Not enough argument. Type ''help spm_superres_lib'' for help.');
end
id = varargin{1};
varargin = varargin(2:end);
switch lower(id)
case 'alloc_vars'
[varargout{1:nargout}] = alloc_vars(varargin{:});
case 'apply_affine'
[varargout{1:nargout}] = apply_affine(varargin{:});
case 'check_do_write'
[varargout{1:nargout}] = check_do_write(varargin{:});
case 'coreg_input'
[varargout{1:nargout}] = coreg_input(varargin{:});
case 'create_nii'
[varargout{1:nargout}] = create_nii(varargin{:});
case 'diffoperator'
[varargout{1:nargout}] = diffoperator(varargin{:});
case 'estimate_model_parameters'
[varargout{1:nargout}] = estimate_model_parameters(varargin{:});
case 'get_dat'
[varargout{1:nargout}] = get_dat(varargin{:});
case 'get_ll'
[varargout{1:nargout}] = get_ll(varargin{:});
case 'get_msk'
[varargout{1:nargout}] = get_msk(varargin{:});
case 'get_nii'
[varargout{1:nargout}] = get_nii(varargin{:});
case 'get_opt'
[varargout{1:nargout}] = get_opt(varargin{:});
case 'parse_input'
[varargout{1:nargout}] = parse_input(varargin{:});
case 'pm'
[varargout{1:nargout}] = pm(varargin{:});
case 'put_nii'
[varargout{1:nargout}] = put_nii(varargin{:});
case 'show_stuff'
[varargout{1:nargout}] = show_stuff(varargin{:});
otherwise
help spm_superres_lib
error('Unknown function %s. Type ''help spm_superres_lib'' for help.', id)
end
end
%==========================================================================
%==========================================================================
% alloc_vars()
function [Nii_y,Nii_z,Nii_w,Nii_Dy,Nii_H] = alloc_vars(WriteTmpNii,Nii_x,dm,mat,DirOut,Verbose)
if Verbose, fprintf('Allocating niftis...'); end
if ~(exist(DirOut,'dir') == 7) && ~isempty(DirOut)
mkdir(DirOut);
end
C = numel(Nii_x);
Nii_y = {nifti};
if WriteTmpNii
Nii_z = {nifti};
Nii_w = {nifti};
Nii_Dy = {nifti};
Nii_H = {nifti};
else
Nii_z = {struct};
Nii_w = {struct};
Nii_Dy = {struct};
Nii_H = {struct};
end
for c=1:C
if isstruct(Nii_x{c}(1))
f = Nii_x{c}(1).fname;
else
f = ['img' num2str(c) '.nii'];
end
[pth,nam] = fileparts(char(f));
if ~isempty(DirOut)
pth = DirOut;
end
fname_y = fullfile(pth,['y' nam '.nii']);
create_nii(fname_y,zeros(dm(1:3),'single'),mat,[spm_type('float32') spm_platform('bigend')],'y');
Nii_y{c} = nifti(fname_y);
if WriteTmpNii
fname_z = fullfile(pth,['z' nam '.nii']);
fname_w = fullfile(pth,['w' nam '.nii']);
fname_Dy = fullfile(pth,['Dy' nam '.nii']);
fname_H = fullfile(pth,['H' nam '.nii']);
create_nii(fname_z,zeros( [dm(1:3) 3],'single'),mat,[spm_type('float32') spm_platform('bigend')],'z');
create_nii(fname_w,zeros( [dm(1:3) 3],'single'),mat,[spm_type('float32') spm_platform('bigend')],'w');
create_nii(fname_Dy,zeros([dm(1:3) 3],'single'),mat,[spm_type('float32') spm_platform('bigend')],'Dy');
create_nii(fname_H,zeros( dm(1:3), 'single'),mat,[spm_type('float32') spm_platform('bigend')],'H');
Nii_z{c} = nifti(fname_z);
Nii_w{c} = nifti(fname_w);
Nii_Dy{c} = nifti(fname_Dy);
Nii_H{c} = nifti(fname_H);
else
Nii_z{c}.dat = zeros([dm(1:3) 3],'single');
Nii_w{c}.dat = zeros([dm(1:3) 3],'single');
Nii_Dy{c}.dat = zeros([dm(1:3) 3],'single');
Nii_H{c}.dat = zeros(dm(1:3),'single');
end
end
if Verbose, fprintf('done!\n'); end
end
%==========================================================================
%==========================================================================
% apply_affine()
function y = apply_affine(M,dm)
[x0,y0,z0] = ndgrid(single(1:dm(1)),...
single(1:dm(2)),...
single(1:dm(3)));
y = cat(4,M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4), ...
M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4), ...
M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4));
if dm(3) == 1
y(:,:,:,end) = 1;
end
end
%==========================================================================
%==========================================================================
% check_do_write()
function do_write = check_do_write(C,dm,memmx,nw)
% z C*dm*3*4b
% w C*dm*3*4b
% Dy C*dm*3*4b
% H C*dm*4b
% and X and Y
nm = prod(dm);
unt = 4; % One float is four bytes
memreq = C*nm*3*unt + C*nm*3*unt + C*nm*3*unt + C*nm*unt + 2*min(min(nw,32),C)*nm*unt;
memreq = memreq/1e6;
if memreq > memmx
do_write = true;
else
do_write = false;
end
end
%==========================================================================
%==========================================================================
% coreg_input()
function R = coreg_input(Nii_x,DoCoReg,ref)
if nargin < 3, ref = [1 1]; end
C = numel(Nii_x);
R = cell(1,C);
for c=1:C
N = numel(Nii_x{c});
R{c} = cell(1,N);
R{c}(:) = {eye(4)};
end
if Nii_x{1}(1).dim(3) > 1
Vr = Nii_x{ref(1)}(ref(2));
for c=1:C
N = numel(Nii_x{c});
for n=1:N
if (c == ref(1) && n == ref(2)) || ~DoCoReg
continue
else
Vm = Nii_x{c}(n);
x = spm_coreg(Vr,Vm);
R{c}{n} = spm_matrix(x(:)');
end
end
end
end
end
%==========================================================================
%==========================================================================
% create_nii()
function Nii = create_nii(pth,dat,mat,dtype,descrip,offset,scl_slope,scl_inter)
if nargin<6, offset = 0; end
if nargin<7, scl_slope = 1; end
if nargin<8, scl_inter = 0; end
if exist(pth,'file')==2, delete(pth); end
Nii = nifti;
dm = size(dat);
Nii.dat = file_array(pth,dm,dtype,offset,scl_slope,scl_inter);
Nii.mat = mat;
Nii.mat0 = mat;
Nii.descrip = descrip;
create(Nii);
Nii.dat(:) = dat(:);
end
%==========================================================================
%==========================================================================
% diffoperator()
function out = diffoperator(in,dm,vx,lam,type)
Dx = sparse(toeplitz([-1 1 zeros(1,dm(1)-2)],[-1 zeros(1,dm(1)-1)]))/vx(1); Dx(1,1)=0;
Dy = sparse(toeplitz([-1 1 zeros(1,dm(2)-2)],[-1 zeros(1,dm(2)-1)]))/vx(2); Dy(1,1)=0;
if dm(3) == 1
Dz = sparse(0);
else
Dz = sparse(toeplitz([-1 1 zeros(1,dm(3)-2)],[-1 zeros(1,dm(3)-1)]))/vx(3); Dz(1,1)=0;
end
D = lam*[kron(speye(dm(3)),kron(speye(dm(2)),Dx ))
kron(speye(dm(3)),kron(Dy, speye(dm(1))))
kron(Dz, kron(speye(dm(2)),speye(dm(1))))];
clear Dx Dy Dz
if strcmp(type,'D')
out = full(reshape(D*double(in(:)),[dm(1:3) 3]));
elseif strcmp(type,'Dt')
out = full(reshape(D'*double(in(:)),dm(1:3)));
else
error('Input error!');
end
out = single(out);
end
%==========================================================================
%==========================================================================
% estimate_model_parameters()
function [tau,lam,rho] = estimate_model_parameters(Nii,LamScl,RhoScl,NumWorkers,Verbose)
C = numel(Nii);
tau = cell(1,C);
lam = cell(1,C);
info = cell(1,C);
parfor (c=1:C,NumWorkers)
% Estimate MR image noise
[NoiseStd,mu,info{c}] = noise_estimate(Nii{c});
tau{c} = 1./(NoiseStd.^2);
lam{c} = LamScl/double(mean(mu));
% % Scale with number of observations to give a little more weight to the
% % prior when there are multiple observations of the same channel
% lam{c} = sqrt(N)*lam{c};
if Verbose
N = numel(Nii{c});
for n=1:N
fprintf('c=%i, i=%i | sd=%f, mu=%f -> tau=%f, lam=%f\n', c, n, NoiseStd(n), mu(n), tau{c}(n), lam{c});
end
end
end
if Verbose >= 2
%---------------------------
% Show fit(s)
%---------------------------
figname = '(spm_superres) Parameter estimates';
fig = findobj('Type', 'Figure', 'Name', figname);
if isempty(fig), fig = figure('Name', figname, 'NumberTitle', 'off'); end
set(0, 'CurrentFigure', fig);
N0 = 0;
for c=1:C
N = numel(Nii{c});
for n=1:N
N0 = N0 + 1;
end
end
nr = floor(sqrt(N0));
nc = ceil(N0/nr);
cnt = 1;
for c=1:C
N = numel(Nii{c});
for n=1:N
subplot(nr,nc,cnt);
plot(info{c}(n).x(:),info{c}(n).h/sum(info{c}(n).h)/info{c}(n).md,'b.', ...
info{c}(n).x(:),info{c}(n).sp,'r', ...
info{c}(n).x(:),info{c}(n).p,'--');
% FontSize = 18;
% set(gcf, 'Color', 'w')
% set(gca,'FontSize',FontSize)
% legend('Empirical','Mixture fit','Air class','Brain class')
% xlabel('Image intensity')
% title('RMM Fitted to MRI Intensity Histogram')
cnt = cnt + 1;
end
end
drawnow
end
atau = [];
for c=1:C
N = numel(tau{c});
for n=1:N
atau = [atau tau{c}(n)];
end
end
% This value of rho seems to lead to reasonably good convergence
rho = RhoScl*sqrt(mean(atau(:)))/mean(cell2mat(lam));
if Verbose
fprintf('step-size -> rho=%f\n', rho);
end
end
%==========================================================================
%==========================================================================
% get_dat()
function [dat,dm,mat,vx] = get_dat(Nii_x,R,VoxSize,Inplane1mm,Denoise)
C = numel(Nii_x);
D = cell(1,C);
for c=1:C
N = numel(Nii_x{c});
D{c} = cell(1,N);
D{c}(:) = {eye(4)};
end
if Inplane1mm && ~Denoise
%---------------------------
% Make sure that inplane voxel size is one
%---------------------------
D = cell(1,C);
for c=1:C
N = numel(Nii_x{c});
D{c} = cell(1,N);
for n=1:N
mat = Nii_x{c}(n).mat;
vxc = sqrt(sum(mat(1:3,1:3).^2));
% Get down-sampling factor
d = vxc(1:2);
if d(1)>=1, d(1) = 1; end
if d(2)>=1, d(2) = 1; end
d(3) = 1;
% NN downsampling
D1 = diag([d, 1]);
D{c}{n} = D1;
end
end
end
%---------------------------
% Check if projection matrices need to be used
%---------------------------
vx = [];
dm = [];
for c=1:C
N = numel(Nii_x{c});
for n=1:N
vxc = sqrt(sum(Nii_x{c}(n).mat(1:3,1:3).^2)); % Voxel sizes
dmc = Nii_x{c}(n).dim; % Image size
dmc = [dmc 1];
vx = [vx; round(vxc*10^2)/10^2];
dm = [dm; dmc];
end
end
if VoxSize == 0
% Set super-resolved images voxel size to smallest available
VoxSize = min(min(vx));
end
vx = unique(vx,'rows');
dm = unique(dm,'rows');
%---------------------------
% Build projection matrix struct (dat)
%---------------------------
use_projmat = ~(size(dm,1) == 1 && all(vx == 1)) && ~Denoise;
if ~use_projmat
% No need to use projection matrices
dat = struct;
for c=1:C
N = numel(Nii_x{c});
for n=1:N
dat(c).A(n).do_pm = false;
end
end
mat = Nii_x{1}(1).mat; % Orientation matrix are the same for all images
else
% Images are different size and/or different voxel size, use projection
% matrices
[mat,dm,vx] = max_bb_orient(Nii_x,R,D,VoxSize);
dat = init_dat(Nii_x,mat,dm,R,D);
end
end
%==========================================================================
%==========================================================================
% get_ll()
function [ll1,ll2,ll] = get_ll(Nii_x,Nii_y,Nii_Dy,tau,dat,NumWorkers,Inplane1mm)
% log posterior
C = numel(Nii_y);
ll1 = 0;
ll2 = 0;
parfor (c=1:C,NumWorkers)
% for c=1:C, fprintf('OBS: for!\n')
y = get_nii(Nii_y{c});
for n=1:numel(Nii_x{c})
datcn = dat(c).A(n);
x = get_nii(Nii_x{c}(n));
if Inplane1mm && datcn.do_pm
% Downsample observed data to have 1 mm inplane
% resolution
y0 = double(apply_affine(datcn.D,datcn.dm(1:3)));
x = spm_bsplins(double(x),y0(:,:,:,1),y0(:,:,:,2),y0(:,:,:,3),[0 0 0 0 0 0]);
x = single(x);
y0 = [];
end
msk = get_msk(x);
Ay = pm('A',y,dat(c).A(n));
ll1 = ll1 + (tau{c}(n)/2)*sum(sum(sum((double(x(msk)) - double(Ay(msk))).^2)));
x = [];
Ay = [];
end
y = [];
Dy = get_nii(Nii_Dy{c});
ll2 = ll2 + sum(Dy.^2,4);
Dy = [];
end
ll2 = sum(sum(sum(double(sqrt(ll2)),3),2),1);
ll1 = -ll1;
ll2 = -ll2;
ll = ll1 + ll2;
end
%==========================================================================
%==========================================================================
% get_msk()
function msk = get_msk(in)
msk = isfinite(in) & in ~= 0;
end
%==========================================================================
%==========================================================================
% get_nii()
function img = get_nii(nii)
if isa(nii, 'nifti') || (isstruct(nii) && ~isfield(nii, 'private'))
nii = nii.dat;
end
if isstruct(nii)
img = single(spm_read_vols(nii));
else
[idx{1:ndims(nii)}] = deal(':');
img = single(subsref(nii,struct('type','()','subs',{idx})));
end
% if isa(nii, 'nifti')
% img = single(nii.dat());
% elseif isstruct(nii)
% if isfield(nii, 'private')
% img = single(spm_read_vols(nii));
% else
% img = single(nii.dat());
% end
% else
% img = single(nii());
% end
end
%==========================================================================
%==========================================================================
% get_opt()
function opt = get_opt(opt)
% scaling of regularisation parameter (lambda)
if ~isfield(opt,'LamScl'), opt.LamScl = 10; end
% scaling of step-size parameter (rho)
if ~isfield(opt,'RhoScl'), opt.RhoScl = 1; end
% Max number of iterations
if ~isfield(opt,'MaxNiter'), opt.MaxNiter = 30; end
% Newton iterations
if ~isfield(opt,'NiterNewton'), opt.NiterNewton = 1; end
% Convergence threshold
if ~isfield(opt,'Tolerance'), opt.Tolerance = 1e-4; end
% Run either MTV or indepentend TV denoising
if ~isfield(opt,'DoMTV'), opt.DoMTV = true; end
% Directory where to write output (and temporary files, which are deleted at end of algorithm)
if ~isfield(opt,'DirOut'), opt.DirOut = ''; end
% Clean reference image
if ~isfield(opt,'Nii_y0'), opt.Nii_y0 = []; end
% Number of parfor workers
if ~isfield(opt,'NumWorkers'), opt.NumWorkers = 8; end
% Show stuff
if ~isfield(opt,'Verbose'), opt.Verbose = 1; end
% Do preprocessing (register)
if ~isfield(opt,'DoCoReg'), opt.DoCoReg = true; end
% Show one image, zoomed in
if ~isfield(opt,'ShowZoomed'), opt.ShowZoomed = false; end
% Memory limit for when to allocate variables as niftis
if ~isfield(opt,'MaxMem'), opt.MaxMem = 4096; end
% Reconstruction voxel size, if 0, set to smallest available
if ~isfield(opt,'VoxSize'), opt.VoxSize = 1; end
% Downsample inplane resolution to 1 mm
if ~isfield(opt,'Inplane1mm'), opt.Inplane1mm = true; end
% Do just denoising, without super-resolving
if ~isfield(opt,'Denoise'), opt.Denoise = false; end
end
%==========================================================================
%==========================================================================
% parse_input()
function Nii = parse_input(pths)
if iscell(pths)
C = numel(pths);
Nii = cell(1,C);
for c=1:C
Nii{c} = spm_vol(pths{c});
end
elseif ischar(pths) && (exist(pths,'dir') == 7)
dirs = spm_select('List',pths,'dir');
C = size(dirs,1);
if C > 0
Nii = cell(1,C);
for c=1:C
d = deblank(dirs(c,:));
d = fullfile(pths,d);
files = spm_select('FPList',d,'^.*\.nii$');
Nii{c} = spm_vol(files);
end
else
files = spm_select('FPList',pths,'^.*\.nii$');
C = size(files,1);
Nii = cell(1,C);
for c=1:C
f = deblank(files(c,:));
Nii{c} = spm_vol(f);
end
end
else
error('Input error!')
end
end
%==========================================================================
%==========================================================================
% pm()
function varargout = pm(nam,varargin)
if strcmp(nam,'A')
%---------------------------
% Forward operator
%---------------------------
% Parse input
y = varargin{1};
A = varargin{2};
if A.do_pm
x = apply_proj(y,A,nam);
else
% Identity
x = y;
end
% Make output
varargout{1} = x;
elseif strcmp(nam,'At')
%---------------------------
% Adjoint operator
%---------------------------
% Parse input
x = varargin{1};
A = varargin{2};
if A.do_pm
y = apply_proj(x,A,nam);
else
% Identity
y = x;
end
% Make output
varargout{1} = y;
else
error('Input argument error!')
end
end
%==========================================================================
%==========================================================================
% put_nii()
function nii = put_nii(nii,img)
if isa(nii, 'nifti')
nii.dat(:) = img(:);
elseif isstruct(nii)
if isfield(nii, 'private')
nii = spm_write_vol(nii,img);
else
nii.dat(:) = img(:);
end
else
nii = img;
end
end
%==========================================================================
%==========================================================================
% show_stuff()
function show_stuff(in,nam,np,verbose,ShowZoomed,isrgb,nr,nc,figname)
if nargin < 4, verbose = 2; end
if nargin < 5, ShowZoomed = false; end
if nargin < 6, isrgb = false; end
if nargin < 7, nr = 2; end
if nargin < 8, nc = 2; end
if nargin < 9, figname = '(spm_superres) Algorithm progress'; end
if verbose >= 2
fig = findobj('Type', 'Figure', 'Name', figname);
if isempty(fig), fig = figure('Name', figname, 'NumberTitle', 'off'); end
set(0, 'CurrentFigure', fig);
if isempty(in)
clf(fig);
return
end
subplot(nr,nc,np);
if strcmp(nam,'ll')
plot(in(min(3,numel(in)):end),'LineWidth',2);
else
if ShowZoomed
if iscell(in)
im = get_nii(in{1}(1));
mx = max(im(:));
if mx == 0
mx = 1;
end
im = im/mx;
else
mx = max(in(:));
if mx == 0
mx = 1;
end
im = in/mx;
end
dm = size(im);
val = 0.25;
y = floor(val*dm(2):dm(2) - val*dm(2));
x = floor(val*dm(1):dm(1) - val*dm(1));
im = im(x,y,:);
else
if iscell(in)
C = numel(in);
im = [];
for c=1:C
N = numel(in{c});
for n=1:N
imn = get_nii(in{c}(n));
mx = max(imn(:));
if mx == 0
mx = 1;
end
im = cat(4,im,imn/mx);
end
end
else
mx = max(in(:));
if mx == 0
mx = 1;
end
im = in/mx;
end
end
dm = size(im);
dm = [dm 1];
z = round(dm(3)/2);
if isrgb
imshow(squeeze(im(:,:,z,:)));
else
if size(im,3) == 1 && size(im,4) == 1
imagesc(im);
else
montage(squeeze(im(:,:,z,:)),'DisplayRange',[0 max(im(:)) + eps]);
end
colormap(gray);
end
axis off image;
end
title(nam)
drawnow
end
end
%==========================================================================
%==========================================================================
%
% Utility functions
%
%==========================================================================
%==========================================================================
% apply_proj()
function out = apply_proj(in,A,method)
spm_diffeo('bound',1); % OK?
spm_field('bound',1); % match the gradient operator
% Projection parameters
R = A.R;
Mmu = A.mat0;
Mf = A.mat;
dmmu = A.dm0;
dmf = A.dm;
vsmu = sqrt(sum(Mmu(1:3,1:3).^2));
vsf = sqrt(sum(Mf(1:3,1:3).^2));
scl = abs(det(Mmu(1:3,1:3)))^(1/3);
samp = vsf./scl;
samp(samp < 1) = 1;
D = diag([samp 1]);
% smo = sqrt(max(scl.^2-vsf.^2,0))*sqrt(8*log(2));
smo = vsf./scl;
smo(smo <= 1) = 0;
[~,ix] = max(smo);
gap = 1/3;
% smo(ix) = smo(ix) - gap*smo(ix);
sd = smo./(2*sqrt(2*log(2)));
sdscl = 4;
off = -(sdscl*sd)';
Moff = eye(4);
Moff(1:3,4) = off;
dmoff = ceil((D(1:3,1:3)*dmf(1:3)')' + 2*sdscl.*sd);
% dmoff = ceil((D(1:3,1:3)*dmf(1:3)')');
% Verbose options
verbose = false;
nr = 2;
nc = 2;
plotnum = 1;
fignum = 666;
% Do projection, either A or At
if strcmp(method,'A')
if verbose
% Verbose
show_res(in,fignum,nr,nc,plotnum,'in (A)');
plotnum = plotnum + 1;
end
% Pull to subject space (with template space resolution)
Ty = Mmu\(R\(Mf/D));
Ty = Ty*Moff;
dmy = dmoff;
out = spm_diffeo('pull',in,apply_affine(Ty,dmy));
if verbose
% Verbose
show_res(out,fignum,nr,nc,plotnum,'pull1 (A)');
plotnum = plotnum + 1;
end
% Apply slice-profile
spm_smooth(out,out,smo);
if verbose
% Verbose
show_res(out,fignum,nr,nc,plotnum,'smooth (A)');
plotnum = plotnum + 1;
end
% Pull to subject space resolution
Ty = D;
Ty = Moff\Ty;
dmy = dmf;
out = spm_diffeo('pull',out,apply_affine(Ty,dmy));
% out = out(1:D(1,1):end,1:D(2,2):end,1:D(3,3):end);
if verbose
% Verbose
show_res(out,fignum,nr,nc,plotnum,'pull2 (A)');
plotnum = plotnum + 1;
end
elseif strcmp(method,'At')
fignum = fignum + 1;
if verbose
% Verbose
show_res(in,fignum,nr,nc,plotnum,'in (At)');
plotnum = plotnum + 1;
end
% Push to template space resolution
Ty = D;
Ty = Moff\Ty;
dmy = dmoff;
out = spm_diffeo('push',in,apply_affine(Ty,dmf),dmy);
% out = zeros(dmy,'single');
% out(1:D(1,1):end,1:D(2,2):end,1:D(3,3)) = in;
if verbose
% Verbose
show_res(out,fignum,nr,nc,plotnum,'push1 (At)');
plotnum = plotnum + 1;
end
% Apply slice-profile
spm_smooth(out,out,smo);
if verbose
% Verbose
show_res(out,fignum,nr,nc,plotnum,'smooth (At)');
plotnum = plotnum + 1;
end
% Push to template space (with subject space resolution)
Ty = Mmu\(R\(Mf/D));
Ty = Ty*Moff;
dmy = dmoff;
out = spm_diffeo('push',out,apply_affine(Ty,dmy),dmmu);
if verbose
% Verbose
show_res(out,fignum,nr,nc,plotnum,'push2 (At)');
plotnum = plotnum + 1;
end
end
%---------------------------
% Nested functions
%---------------------------
function show_res(in,fignum,nr,nc,plotnum,nam,ix)
if nargin < 6, nam = ''; end
if nargin < 7, ix = [1 2 3]; end
figure(fignum);
subplot(nr,nc,plotnum);
imagesc(permute(in,ix)); axis off xy image; colormap(gray);
title(nam);
end
function check_adjoint(dat,n)
u = randn(dat.dm, 'single');
v = randn(dat.A(n).dm, 'single');
Au = apply_proj(u,dat,n,'A');
Atv = apply_proj(v,dat,n,'At');
v_dot_Au = v(:)' * Au(:);
Atv_dot_v = Atv(:)' * u(:);
disp(v_dot_Au - Atv_dot_v)
end
end
%==========================================================================
%==========================================================================
% blur_fun()
function f = blur_fun(dm,mat,vx)
if nargin<1, dm = [64 64]; end
if nargin<2, mat = eye(numel(dm)); end
if nargin<3, vx = ones(1,numel(dm)); end
if any(size(mat)~=numel(dm)) || numel(vx)~=numel(dm), error('Incompatible dimensions.'); end
% Grid in frequency space
r = cell(1,numel(dm));
for i=1:numel(dm)
r{i} = single([0:ceil(dm(i)/2-1) -floor(dm(i)/2):-1]'*pi/dm(i));
end
X = cell(1,numel(dm));
[X{:}] = ndgrid(r{:});
clear r
% Transform
Y = cell(size(X));
for i=1:numel(dm)
Y{i} = single(0);
for j=1:numel(dm)
Y{i} = Y{i} + mat(i,j)*X{j};
end
end
clear X
% Window function
f = single(0);
for i=1:numel(dm)
f = f + Y{i}.^2;
end
f = ((cos(min(f,pi^2/4)*4/pi) + 1)/2);
% Incorporate voxel size
for i=1:numel(dm)
tmp = sin((vx(i))*Y{i})./(Y{i}.*cos(Y{i}/pi^(1/2)));
tmp(~isfinite(tmp)) = vx(i);
f = f.*tmp;
end
end
%==========================================================================
%==========================================================================
% get_slice_gap()
function gap = get_slice_gap(gap,Nii_x,gapunit)
% Construct slice-gap
% _______________________________________________________________________
% Copyright (C) 2018 Wellcome Trust Centre for Neuroimaging
C = numel(Nii_x);
if isscalar(gap)
% Find thick-slice direction automatically
G = cell(1,C);
for c=1:C
N = numel(Nii_x{c});
G{c} = cell(1,N);
for n=1:N
G{c}{n} = zeros(1,3);
thickslice_dir = get_thickslice_dir(Nii_x{c}(n));
G{c}{n}(thickslice_dir) = gap;
end
end
gap = G;
else
% x-, y-, z-directions given
gap = padarray(gap, [0 max(0,C-numel(gap))], 'replicate', 'post');
for c=1:C
if ~iscell(gap{c})
gap{c} = {gap{c}};
end
gap{c} = padarray(gap{c}, [0 max(0,numel(Nii_x{c})-numel(gap{c}))], 'replicate', 'post');
for i=1:numel(gap{c})
if isempty(gap{c}{i})
gap{c}{i} = 0;
end
gap{c}{i} = padarray(gap{c}{i}, [0 max(0,3-numel(gap{c}{i}))], 'replicate', 'post');
end
end
end
if strcmp(gapunit,'%')
% Convert from percentage to mm
for c=1:C
N = numel(Nii_x{c});
for n=1:N
mat = Nii_x{c}(n).mat;
vx = sqrt(sum(mat(1:3,1:3).^2));
gap{c}{n} = vx.*gap{c}{n};
end
end
end
end
%==========================================================================
%==========================================================================
% get_thickslice_dir()
function thickslice_dir = get_thickslice_dir(Nii)
mat = Nii.mat;
vx = sqrt(sum(mat(1:3,1:3).^2));
[~,thickslice_dir] = max(vx);
end
%==========================================================================
%==========================================================================
% get_window()
function window = get_window(window,Nii_x)
% Construct slice-profile
% _______________________________________________________________________
% Copyright (C) 2018 Wellcome Trust Centre for Neuroimaging
C = numel(Nii_x);
if isempty(window)
% Find thick-slice direction automatically and set defaults:
% In-plane: Gaussian, Through-plane: Rectangle
W = cell(1,C);
for c=1:C
N = numel(Nii_x{c});
W{c} = cell(1,N);