-
Notifications
You must be signed in to change notification settings - Fork 8
/
atemplateobj.m
4806 lines (3935 loc) · 165 KB
/
atemplateobj.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
classdef atemplateobj < handle
% Add networks and overlays to a smoothed brain mesh or gifti object.
%
% Plots: volumes, surfaces, overlays, networks, labels, videos.
% Examples and usages below.
%
% If you get errors using the mex files, delete them.
% Now uses fieldtrip to read nifti's.
%
% General usage:
% - Specify inputs as 'PropertyName', 'PropoertyValue' pairs.
% - Things you can define:
%
% (a.) The brain mesh, using the 'mesh' flag, followed by one of these:
% (1) a triangulated mesh
% (2) gifti object
% (3) nifti volume
% (4) nifti/gifti filename
% (5) flag for a built in default mesh: use 'def1' to 'def6'
%
% (b.) A functional overlay, using the 'overlay' flag, followed by the
% overlay values. (This should also be accompanied by the 'method' flag,
% describing the method to use to project onto the surface, see [c] ).
% (1) a 3D functional volume or the name of a nifti. atemplate
% will automatically define some source positions.
% (2) A vector of overlay values, along with a list of source
% vertices (nx3) for each corresponding functional values. this
% option also requires the 'sourcemodel' flag, for example:
% atemplate('mesh','def1','overlay',OverlayVector,'sourcemodel',MyNx3ListOfPositions)
% (3) Both an overlay vector AND curvature, with a theshold
% supplied. This will project colour for the overlay and
% grayscale curvature elsewhere (like freesurfer):
% atemplate('overlay',{'curvature',FunVol},'method','spheres','thresh',thr)
%
% (c.) For overlays, there are multiple options for projecting from
% source positions/volumes ontoa surface. This can be specified by the
% 'method' flag, followed by:
% (1) 'raycast' - a ray casting routine (default)
% (2) 'spheres' - inflated spheres
% (3) 'euclidean' - a trap-radius distance method
%
% (d.) Functional overlay values belonging to the AAL, HCP250 or
% HarvardOxford atlas. Use the 'overlay' flag, followed by a vector of
% functional values to plot. Also provide the 'method' flag, followed by
% the name of the atlas:
% (1) atemplate('overlay',randi([-4 4],90,1),'method',{'AAL90','raycast'})
% - note must still provide a projection method in most cases
% (2) as above, but using 'method',{'harvard_oxford','raycast'}
% (3) as above, but using 'method',{'aal116','raycast'}
% (4) as above, but using 'method',{'hoa_cerebellum','raycast'} - HarOx with cerebellum
% (5) as above, but using 'method',{'hcp250','raycast'}
%
% (6*) special case: when using AAL90 atlas data with default mesh 1 or 4
% there are precomputed parcels, use:
% atemplate('overlay',t,'method',{'aal_super',[]})
%
% (e.) A Network, using the flag 'network' and provide:
% (1) an NxN matrix, along with a sourcemodel using the
% 'sourcemodel' flag
% (2) filename of a .edge file
% (3) example call: atemplate('network',N,'sourcemodel',v)
% (4) Provide additional flag 'curved' and 1/0 to make the lines bendy
%
% (f.) Nodes to accompany a network, using flag 'nodes':
% (1) atemplate('nodes',Vector/Matrix,'sourcemodel',Sources...)
%
% (.g) OTHER OPTIONS (see bottom of script and example in folder):
% (1) display only one hemisphere, flag 'hemi' and 'l'/'r'
% (2) provide both sources and list of ROI indices in the
% sourcemodel flag, e.g. {v,vi}
% (3) project to atlas space
% (4) provide a parcellation and have functional overlay
% registered to it / return parcellated data from non, use flag
% 'post_parcel',{v vi}
% (5) if rendering overlay and network from different
% sourcemodels, provide network sources using 'net_pos' flag
%
% SCROLL TO THE BOTTOM OF THIS FILE FOR A LONGER HELP AND MORE METHODS.
% Alexander Shaw [[email protected] | github.com/alexandershaw4]
properties
in
data
end
methods
function obj = atemplateobj(varargin)
% defaults
%--------------------------------------------------------------------------
data = struct; % main output structure
in.pmesh = 1; % flag to display the mesh or not
in.labels = 0; % flag to display labels on rois
in.write = 0; % flag to write mesh & overlay
in.fname = []; % filename for saves (e.g. for sae gifti)
in.fighnd = []; % put the plot into an existing figure handle
in.colbar = 1; % display colourbar
in.template = 0; % register source model to a template using ICP
in.orthog = 0; % orthogonalise [ignore]
in.inflate = 0; % inflate the mesh [just calls spm_mesh_inflate]
in.inflate_n = 200;
in.peaks = 0; % compute peaks on surface functional overlay
in.components = 0; % compute local maxima on functional overlay
in.pca = 0; % compute pca on surface functional overlay
in.flip = 0; % ignore
in.affine = 0; % supply affine transformation matrix
in.netcmap = 0; % colormap for network
in.method = 'raycast'; % volume to surface algorithm
in.depth = []; % depth for raycasting
in.all_roi_tissueindex = []; % indices of roi each voxel belongs to
in.thelabels = []; % supply cell array of labels for rois
in.tf_interactive = 0; % ignore
in.checkori = 0; % interactively check/adjust orientation of mesh
in.fillholes = 0; % fill holes in mesh
in.hemi = 'both'; % hemisphere to plot
in.roi = []; % roi list
in.optimise = 0; % explicitly optimise the alignments (gradient descent)
in.post_parcel = []; % parcellate an overlay post-projection
in.thresh = []; % only display top % /threshold
in.open = 0; % open the 2 hemispheres, i.e 2 plots
in.verbose = 0; % print everything it does...
in.dosphere = 0;
in.allsides = 0;
in.curvednet = 0;
in.netscale = [];
in.netthresh = [];
in.netthresh_nonzero = [];
in.boundary = [];
% specified inputs [override defaults]
%--------------------------------------------------------------------------
for i = 1:length(varargin)
if strcmp(varargin{i},'overlay'); in.L = varargin{i+1}; end
if strcmp(varargin{i},'verbose'); in.verbose = varargin{i+1}; end
if strcmp(varargin{i},'dosphere'); in.dosphere = 1; end
if strcmp(varargin{i},'open'); in.open= 1; end
if strcmp(varargin{i},'allsides'); in.allsides= 1; end
if strcmp(varargin{i},'hemi'); in.hemi= varargin{i+1}; end
if strcmp(varargin{i},'peaks'); in.peaks = 1; end
if strcmp(varargin{i},'sourcemodel'); in.pos = varargin{i+1}; end
if strcmp(varargin{i},'netthresh'); in.netthresh = varargin{i+1}; end
if strcmp(varargin{i},'netthresh_nonzero'); in.netthresh_nonzero = varargin{i+1}; end
if strcmp(varargin{i},'roi'); in.roi = varargin{i+1}; end
if strcmp(varargin{i},'network'); in.A = varargin{i+1}; end
if strcmp(varargin{i},'netscale'); in.netscale = varargin{i+1};end
if strcmp(varargin{i},'net_pos'); in.net_pos = varargin{i+1}; end
if strcmp(varargin{i},'curved'); in.curvednet = varargin{i+1}; end
if strcmp(varargin{i},'tracks'); in.T = varargin{i+1}; in.H = varargin{i+2}; end
if strcmp(varargin{i},'nosurf'); in.pmesh = 0; end
if strcmp(varargin{i},'nodes'); in.N = varargin{i+1}; end
if strcmp(varargin{i},'gifti'); in.g = varargin{i+1}; end
if strcmp(varargin{i},'mesh'); in.g = varargin{i+1}; end
if strcmp(varargin{i},'boundary'); in.boundary = varargin{i+1};end
if strcmp(varargin{i},'optimise'); in.optimise = varargin{i+1};end
if strcmp(varargin{i},'post_parcel'); in.post_parcel = varargin{i+1};end
if strcmp(varargin{i},'fillholes'); in.fillholes = 1; end
if strcmp(varargin{i},'thresh'); in.thresh = varargin{i+1};end
if strcmp(varargin{i},'affine'); in.affine = varargin{i+1};end
if strcmp(varargin{i},'funcaffine'); in.funcaffine = varargin{i+1}; end
if strcmp(varargin{i},'inflate'); in.inflate = 1; end
if strcmp(varargin{i},'orthog'); in.orthog = varargin{i+1};end
if strcmp(varargin{i},'components'); in.components = 1; end
if strcmp(varargin{i},'pca'); in.pca = 1; end
if strcmp(varargin{i},'flip'); in.flip = 1; end
if strcmp(varargin{i},'checkori'); in.checkori = 1; end
if strcmp(varargin{i},'netcmap'); in.netcmap= varargin{i+1};end
if strcmp(varargin{i},'write'); in.write = 1; in.fname = varargin{i+1}; end
if strcmp(varargin{i},'writestl'); in.write = 2; in.fname = varargin{i+1}; end
if strcmp(varargin{i},'writevrml'); in.write = 3; in.fname = varargin{i+1}; end
if strcmp(varargin{i},'writenii'); in.write = 4; in.fname = varargin{i+1}; end
if strcmp(varargin{i},'fighnd'); in.fighnd = varargin{i+1}; end
if strcmp(varargin{i},'nocolbar'); in.colbar = 0; end
if strcmp(varargin{i},'method'); in.method = varargin{i+1}; end
if strcmp(varargin{i},'depth'); in.depth = varargin{i+1}; end
if strcmp(varargin{i},'video'); in.V = varargin{i+1};
in.fpath = varargin{i+2};
in.times = varargin{i+3}; end
if strcmp(varargin{i},'inflate')
try
if isnumeric(varargin{i+1});in.inflate_n = varargin{i+1};end
end
end
if strcmp(varargin{i},'othermesh'); in.M = varargin{i+1}; in.O = varargin{i+2}; end
if strcmp(varargin{i},'tf_interactive');in.tf_interactive = varargin{i+1}; end
if strcmp(varargin{i},'labels'); in.labels = 1;
try in.all_roi_tissueindex = varargin{i+1};
in.thelabels = varargin{i+2};
end
end
if strcmp(varargin{i},'template')
in.template = 1;
in.model = varargin{i+1};
end
obj.in = in;
obj.data = data;
% % Allow passing of existing atemplate-returned structure
% if isstruct(varargin{i}) && isfield(varargin{i},'in')
% fprintf('User specified plot structure\n');
% data = varargin{i};
% mesh = parse_mesh(data.mesh,data.in,data);
% data = parse_plots(data,data.in);
% return
% end
end
end
function run(obj)
in = obj.in;
data = obj.data;
% Preliminaries & parse functions for plots
%--------------------------------------------------------------------------
data.verbose = in.verbose; % make sure every subfunction knows if verbose mode
if in.open
data = isopen(data,in);
return;
end
if in.allsides
data = allsides(data,in);
return;
end
data = obj.sort_sourcemodel(data,in); % Sourcemodel vertices
[mesh,data] = obj.get_mesh(in,data); % Get Surface
[data,in] = obj.sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = obj.parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = obj.parse_plots(data,in); % Overlays, networks, tracts, nodes, videos etc.
data.in = in; % Return the input options for re-run
% draw boundaries of ROIs
if ~isempty(in.boundary)
iv = in.boundary;
p = [];
end
end
% FUNCTIONS
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function data = isopen(obj,data,in)
% a wrapper on atemplate for generating the same plot for the left and
% right hemis separately in different sublots
s(1) = subplot(121);
s(2) = subplot(122);
data_in = data;
% Plot 1.
in.hemi = 'l';
in.fighnd = s(1);
data = sort_sourcemodel(data_in,in); % Sourcemodel vertices
[mesh,data] = get_mesh(in,data); % Get Surface
[data,in] = sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = parse_plots(data,in); % Overlays, networks, etc
data.in = in; % Return everything
data_l = data;
view([90 0]);
% Plot 2.
in.hemi = 'r';
in.fighnd = s(2);
data = sort_sourcemodel(data_in,in); % Sourcemodel vertices
[mesh,data] = get_mesh(in,data); % Get Surface
[data,in] = sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = parse_plots(data,in); % Overlays, networks, etc
data.in = in; % Return everything
data_r = data;
view([270 0]);
data = [];
data.l = data_l;
data.r = data_r;
end
function data = allsides(obj,data,in)
% a wrapper on atemplate for generating the same plot for the left and
% right hemis separately in different sublots
s = in.fighnd;
data_in = data;
% Plot 1.
in.hemi = 'r';
in.fighnd = s(1);
data = sort_sourcemodel(data_in,in); % Sourcemodel vertices
[mesh,data] = get_mesh(in,data); % Get Surface
[data,in] = sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = parse_plots(data,in); % Overlays, networks, etc
data.in = in; % Return everything
data_l = data;
view([90 0]);
% Plot 2.
in.hemi = 'r';
in.fighnd = s(2);
data = sort_sourcemodel(data_in,in); % Sourcemodel vertices
[mesh,data] = get_mesh(in,data); % Get Surface
[data,in] = sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = parse_plots(data,in); % Overlays, networks, etc
data.in = in; % Return everything
data_l = data;
view([-90 0]);
% Plot 3.
in.hemi = 'l';
in.fighnd = s(3);
data = sort_sourcemodel(data_in,in); % Sourcemodel vertices
[mesh,data] = get_mesh(in,data); % Get Surface
[data,in] = sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = parse_plots(data,in); % Overlays, networks, etc
data.in = in; % Return everything
data_r = data;
view([-270 0]);
% Plot 4.
in.hemi = 'l';
in.fighnd = s(4);
data = sort_sourcemodel(data_in,in); % Sourcemodel vertices
[mesh,data] = get_mesh(in,data); % Get Surface
[data,in] = sort_template(data,in); % Template space? (aal90/78/58)
[mesh,data] = parse_mesh(mesh,in,data); % Mesh to put stuff on
data.mesh = mesh;
data = parse_plots(data,in); % Overlays, networks, etc
data.in = in; % Return everything
data_r = data;
view([270 0]);
data = [];
data.l = data_l;
data.r = data_r;
end
function data = parse_plots(obj,data,i)
% unpack triggers
inputs = i;
% overlays
if isfield(inputs,'L')
% copy over overlay options
data.overlay.peaks = i.peaks;
data.overlay.components = i.components;
data.overlay.pca = i.pca;
data.overlay.method = i.method;
data.overlay.depth = i.depth;
data.overlay.thresh = i.thresh;
data.overlay.tf_interactive = i.tf_interactive;
if isfield(i,'funcaffine')
data.overlay.affine = i.funcaffine;
end
data = overlay(data, (i.L),i.write,i.fname,i.colbar);
end
isover = exist('L','var') || exist('V','var');
if isover && exist('A','var')
i.colbar = 0;
alpha(.2);
end
% networks
if isfield(inputs,'A')
data.network.scale = i.netscale;
data.network.netthresh = i.netthresh;
data.network.netthresh_nonzero = i.netthresh_nonzero;
data = connections(data,i.A,i.colbar,i.write,i.fname,i.netcmap,i.curvednet);
end
% tracts
if isfield(inputs,'T')
data = drawtracks(data,i.T,i.H);
end
% nodes
if isfield(inputs,'N')
data = drawnodes(data, i.N);
end
% labels
data = parse_labels(i,data);
% video
if isfield(inputs,'V')
tv = 1:size(i.V,2);
try tv = i.times; end
data = video(data,i.V,1,i.fpath,tv);
end
end
function data = parse_labels(obj,i,data)
% decide which labels to include depending on what we're plotting
if i.labels
if isfield(i,'A')
if isnumeric(i.A)
data = addlabels(data,i.A,i.all_roi_tissueindex,i.thelabels);
elseif ischar(i.A)
E = data.network.edge;
data = addlabels(data,E,i.all_roi_tissueindex,i.thelabels);
end
elseif isfield(i,'N')
if sum(ismember(size(i.N),[1 90])) == 2
data = addlabels(data, diag(i.N),i.all_roi_tissueindex,i.thelabels);
elseif sum(ismember(size(i.N),[1 90])) == 1
data = addlabels(data, diag(sum(i.N,2)),i.all_roi_tissueindex,i.thelabels);
end
else; n = length(data.sourcemodel.pos);
data = addlabels(data, ones(n,n),i.all_roi_tissueindex,i.thelabels);
end
end
end
function data = sort_sourcemodel(obj,data,i)
% Sort out what source model vertices we're going to use
if isfield(i,'pos')
if i.verbose
fprintf('+Using supplied sourcemodel vertices\n');
end
pos = i.pos;
elseif isfield(i,'A') && ischar(i.A)
if i.verbose
fprintf('+Using coords in node-file as sourcemodel\n');
end
[~,pos] = rw_edgenode(i.A);
pos = pos(:,1:3);
% elseif isfield(i,'L') && ischar(i.L)
% %IF USING A NIFTI OVERLAY AS SOURCEMODEL, NEED THIS *before* TRYING TO DO
% %TEMPLATE SPACE CONVERSION!
%
% [mesh,data] = get_mesh(i,data);
% data.mesh = mesh;
% [~,data] = parse_overlay(i.L,data);
% pos = data.sourcemodel.pos;
else
if i.verbose
fprintf('+Assuming AAL90 source vertices by default\n');
end
load('AAL_SOURCEMOD');
pos = template_sourcemodel.pos;
end
if iscell(pos)
% store 2nd input - vector descrbinig which vertices belong to which rois
data.sourcemodel.vi = pos{2};
pos = pos{1};
end
% Centre sourcemodel
dpos = pos - repmat(spherefit(pos),[size(pos,1),1]);
% Ensure stability if approaching centre (very tiny values)
if ~any(isnan(dpos(:)))
pos = dpos;
end
data.sourcemodel.pos = pos;
% add ability to have network on a separate sourcemodel to overlay
if isfield(i,'net_pos') && size(i.net_pos,2)==3
if i.verbose
fprintf('++Also found a set of source vertices for a network\n');
end
data.sourcemodel.net_pos = i.net_pos;
end
% not hugely revelant here, but use this func to also store data for the
% post-hoc atlas-registration function if required
if iscell(i.post_parcel)
data.post_parcel = i.post_parcel;
end
end
function [mesh,data] = parse_mesh(obj,mesh,i,data)
% Figure out whether we actually want to plot a glass brain mesh, or not
% if only one hemisphere plot
hemi = i.hemi;
data.hemi = hemi;
% if affine supplied or flip flag
affine = i.affine;
flip = i.flip;
% if inflate, pass flag
inflate = i.inflate;
mesh.inflate = i.inflate_n; % allow passing amount to inflate
mesh.do_ball = i.dosphere;
% check orientation?
checkori = i.checkori;
% fill holes during hemisphere separation?
dofillholes = i.fillholes;
% explicitly optimise the alignment of the cloud points?
optimise = i.optimise;
if i.pmesh && ~isfield(i,'T')
[mesh,data.sourcemodel.pos,h,p] = obj.meshmesh(mesh,i.write,i.fname,i.fighnd,...
.3,data.sourcemodel.pos,hemi,affine,flip,inflate,checkori,dofillholes,optimise,i.verbose);
elseif i.pmesh
[mesh,data.sourcemodel.pos,h,p] = obj.meshmesh(mesh,i.write,i.fname,i.fighnd,...
.3,data.sourcemodel.pos,hemi,affine,flip,inflate,checkori,dofillholes,optimise,i.verbose);
else
h = [];
p = [];
end
mesh.h = h;
mesh.p = p;
end
function [mesh, data] = convert_mesh(obj,mesh,data)
% Convert a STRUCTURAL volume to a surface mesh using an isosurface. Take
% some liberties with downsampling and rescaling
if ischar(mesh)
[fp,fn,fe] = fileparts(mesh);
switch fe
case{'.gz'}
if data.verbose
fprintf('-Unpacking .gz\n');
end
gunzip(mesh);
mesh = strrep(mesh,'.gz','');
[mesh, data] = obj.convert_mesh(mesh,data);
return;
case{'.nii','.mri'}
%wb = waitbar(0,'Reading nifti volume...');
% mini switch for load type
switch fe
case '.nii'
% load nifti volume file
if data.verbose
fprintf('-Reading Nifti volume\n');
end
% ni = load_nii(mesh);
% vol = ni.img;
%
% % recover rotation matrix
% b = ni.hdr.hist.quatern_b;
% c = ni.hdr.hist.quatern_c;
% d = ni.hdr.hist.quatern_d;
% x = ni.hdr.hist.qoffset_x;
% y = ni.hdr.hist.qoffset_y;
% z = ni.hdr.hist.qoffset_z;
% a = sqrt(1.0-(b^2+c^2+d^2));
%
% R = [ a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c ;
% 2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b ;
% 2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b ];
% t = [x; y; z];
% just use fieldtrip
ni = ft_read_mri(mesh);
vol = ni.anatomy;
R = ni.transform(1:3,1:3);
t = ni.transform(1:3,end);
% real-world coordinates =
%[x; y; z] = R * [i; j; k] + t
[nx,ny,nz] = size(vol);
% compute edges and linearly interp grid coordinates
E1 = R*[1 ;1 ;1 ]+t;
E2 = R*[nx;ny;nz]+t;
xarr = linspace(E1(1),E2(1),nx);
yarr = linspace(E1(2),E2(2),ny);
zarr = linspace(E1(3),E2(3),nz);
% NEW: subsample volume by 2. This speeds up subsequent patch
% reduction enormously with at relatively little cost to
% resolution
if data.verbose
fprintf('-Subsampling structural volume\n');
end
[xg,yg,zg] = meshgrid(yarr,xarr,zarr);
[NX, NY, NZ, vol] = reducevolume(xg,yg,zg,vol,4);
xarr = linspace(xarr(1),xarr(end),size(vol,1));
yarr = linspace(yarr(1),yarr(end),size(vol,2));
zarr = linspace(zarr(1),zarr(end),size(vol,3));
[X,Y,Z] = meshgrid(yarr,xarr,zarr);
case '.mri'
% load ctf mri file
if data.verbose
fprintf('-Reading CTF_MRI4 volume\n');
end
ni = ft_read_mri(mesh,'dataformat','ctf_mri4');
vol = ni.anatomy;
vol = vol - mean(vol(:));
end
if ndims(vol) ~= 3
fprintf('-Volume has wrong number of dimensions!\nUsing default mesh\n');
mesh = read_nv;
return
end
% bounds:
%waitbar(0.2,wb,'Reading nifti volume: Extracting isosurface');
if data.verbose
fprintf('-Extracting ISO surface\n');
end
B = [min(data.sourcemodel.pos); max(data.sourcemodel.pos)];
try fv = isosurface(X,Y,Z,vol,0.5); % nifti's
catch; fv = isosurface(vol,0.5); % .mri's / other volumes
end
% swap x y
v = fv.vertices;
v = [v(:,2) v(:,1) v(:,3)];
fv.vertices = v;
% reduce vertex density
%waitbar(0.6,wb,'Reading nifti volume: Reducing density');
if data.verbose
fprintf('-Reducing patch density\n');
end
nv = length(fv.vertices);
count = 0;
while nv > 60000
fv = reducepatch(fv, 0.5);
nv = length(fv.vertices);
count = count + 1;
end
%if count > 0
% fprintf('Smoothing surface\n');
% fv.vertices = sms(fv.vertices,fv.faces,1,2);
%end
% print
%waitbar(0.9,wb,'Reading nifti volume: Rescaling');
if data.verbose
fprintf('-Patch reduction finished\n');
fprintf('-Rescaling mesh to sourcemodel\n');
end
v = fv.vertices;
for i = 1:3
v(:,i) = obj.rescale(v(:,i),B(:,i));
end
% return scaled mesh
mesh = [];
mesh.nifti = [fn fe];
mesh.faces = fv.faces;
mesh.vertices = v;
mesh.vol = vol;
data.mesh = mesh;
%close(wb);
case{'.gii'}
% load the gifti
gi = gifti(mesh);
mesh = [];
mesh.faces = gi.faces;
mesh.vertices = gi.vertices;
data.mesh = mesh;
otherwise
% allow shorthands call for default meshes
%-----------------------------------------
if strcmp(lower(mesh),'def') || strcmp(lower(mesh),'def1')
% ICBM152 - smoothed
nmesh = read_nv;
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
if strcmp(lower(mesh),'def2')
% Ch2
nmesh = gifti('BrainMesh_Ch2.gii');
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
if strcmp(lower(mesh),'def3')
% mni152_2009
nmesh = load('mni152_2009','faces','vertices');
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
if strcmp(lower(mesh),'def4')
nmesh = gifti('BrainMesh_ICBM152.gii');
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
if strcmp(lower(mesh),'def5')
nmesh = load('ft_mesh_mni');
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
if strcmp(lower(mesh),'def6')
nmesh = gifti('cortex_8196.surf.gii');
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
if strcmp(lower(mesh),'def7')
nmesh = gifti('bh.headbrain.TPM.gii');
mesh = [];
mesh.vertices = nmesh.vertices;
mesh.faces = nmesh.faces;
end
end
elseif isnumeric(mesh) && ndims(mesh)==3
% bounds:
%wb = waitbar(0,'Reading nifti volume...');
%waitbar(0.2,wb,'Reading nifti volume: Extracting isosurface');
% NEW: subsample volume by 2. This speeds up subsequent patch
% reduction enormously with at relatively little cost to
% resolution
if data.verbose
fprintf('-Subsampling structural volume\n');
end
[NX, NY, NZ, mesh] = reducevolume(mesh,2);
if data.verbose
fprintf('-Extracting ISO surface\n');
end
B = [min(data.sourcemodel.pos); max(data.sourcemodel.pos)];
fv = isosurface(mesh,0.5);
% swap x y
v = fv.vertices;
v = [v(:,2) v(:,1) v(:,3)];
fv.vertices = v;
% reduce vertex density
if data.verbose
fprintf('-Reducing patch density\n');
end
nv = length(fv.vertices);
count = 0;
%waitbar(0.6,wb,'Reading nifti volume: Reducing density');
while nv > 60000
fv = reducepatch(fv, 0.5);
nv = length(fv.vertices);
count = count + 1;
end
% print
if data.verbose
fprintf('-Patch reduction finished\n');
fprintf('-Rescaling mesh to sourcemodel\n');
end
%waitbar(0.9,wb,'Reading nifti volume: Rescaling');
v = fv.vertices;
for i = 1:3
v(:,i) = obj.rescale(v(:,i),B(:,i));
end
% return scaled mesh
mesh = [];
mesh.faces = fv.faces;
mesh.vertices = v;
data.mesh = mesh;
%close(wb);
end
end
function [data,i] = sort_template(obj,data,i)
% If specified a template model, register data to it and return splined data as
% well as weights
if ~isfield(i,'pos')
i.pos = data.sourcemodel.pos;
end
try
data.template.model = i.model;
data.template.labels = i.labels;
end
if i.template
atlas = obj.dotemplate(i.model);
rois = obj.get_roi_centres(atlas.template_sourcemodel.pos,atlas.all_roi_tissueindex);
atlas.template_sourcemodel.pos = rois;
atlas = rmfield(atlas,'all_roi_tissueindex');
reg = obj.interp_template(data.sourcemodel,rois);
atlas.M = reg.M;
data.atlas = atlas;
NM = atlas.M;
% rescale so not change amplitudes
m = max(NM(:));
NM = NM/m;
data.atlas.M = NM;
% generate & apply a ROI mask if requested
%----------------------------------------------------
if isfield(i,'roi') && ~isempty(i.roi)
% should be cell array of labels
if ischar(i.roi)
i.roi = {i.roi};
end
% check rois exist
labs = atlas.AAL_Labels;
for iroi = 1:length(i.roi)
ROI_ind(iroi) = find(strcmp(i.roi{iroi},labs));
if isempty( ROI_ind(iroi) )
fprintf('Requested ROI (%s) not found\n');
end
end
% apply mask!
newM = NM*0;
newM(:,ROI_ind) = NM(:,ROI_ind);
NM = newM;
end
% update sourcemodel and labels
data.sourcemodel = atlas.template_sourcemodel;
if i.labels; i.thelabels = atlas.AAL_Labels; end
% overlay data
if isfield(i,'L')
if isnumeric(i.L) && ndims(i.L) ~= 3
S = [min(i.L(:)) max(i.L(:))];
NL = i.L(:)'*NM;
L = S(1) + ((S(2)-S(1))).*(NL - min(NL))./(max(NL) - min(NL));
L(isnan(L))=0;
i.L = L;
end
end
% network
if isfield(i,'A')
if isnumeric(i.A)
S = [min(i.A(:)) max(i.A(:))];
NL = NM'*i.A*NM;
A = S(1) + ((S(2)-S(1))).*(NL - min(NL(:)))./(max(NL(:)) - min(NL(:)));
A(isnan(A)) = 0;
i.A = A;
end
end
% video data
if isfield(i,'V')
S = [min(i.V(:)) max(i.V(:))];
for j = 1:size(i.V,2) % over time points
NL(:,j) = i.V(:,j)'*NM;
end
V = S(1) + ((S(2)-S(1))).*(NL - min(NL))./(max(NL) - min(NL));
V(isnan(V))=0;
if orthog
% dont use this
V = obj.symm_orthog(V);
end
V(isnan(V))=0;
i.V = V;
end
end
end
function [mesh,data] = get_mesh(obj,i,data)
% Decide what brain we're actually using, return it
try mesh = i.g;
if i.verbose
fprintf('+Using user provided mesh\n');
end
if ischar(mesh) || isnumeric(mesh)
[mesh,data] = obj.convert_mesh(mesh,data);
end
catch mesh = read_nv();
if i.verbose
fprintf('+Using template brain mesh\n');
end
end
% if i.inflate
% try fprintf('Trying to inflate mesh\n');
% dmesh.vertices = mesh.vertices;
% dmesh.faces = mesh.faces;
% dmesh = spm_mesh_inflate(dmesh,100);
% mesh.vertices = dmesh.vertices;
% mesh.faces = dmesh.faces;
% catch
% fprintf('Couldnt find spm_mesh_inflate: is SPM installed?\n');
% end
% end
end
function atlas = dotemplate(obj,model)
% Put dense sourcemodel into an atlas space using ICP and linear
% interpolation
%
%
%
if ischar(model)
switch model
case lower({'aal','aal90'}); load New_AALROI_6mm.mat
case lower('aal58'); load New_58cortical_AALROI_6mm
case lower('aal78'); load New_AALROI_Cortical78_6mm
otherwise
fprintf('Model not found.\n');
return;
end
elseif iscell(model)
template_sourcemodel.pos = model{1};
all_roi_tissueindex = model{2};
AAL_Labels = [];
end
atlas.AAL_Labels = AAL_Labels;
atlas.all_roi_tissueindex = all_roi_tissueindex;
atlas.template_sourcemodel = template_sourcemodel;