forked from fieldtrip/fileio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_read_headshape.m
1405 lines (1247 loc) · 48.7 KB
/
ft_read_headshape.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 [shape] = ft_read_headshape(filename, varargin)
% FT_READ_HEADSHAPE reads the fiducials and/or the measured headshape from a variety
% of files (like CTF and Polhemus). The headshape and fiducials can for example be
% used for coregistration.
%
% Use as
% [shape] = ft_read_headshape(filename, ...)
% or
% [shape] = ft_read_headshape({filename1, filename2}, ...)
%
% If you specify the filename as a cell-array, the following situations are supported:
% - a two-element cell-array with the file names for the left and
% right hemisphere, e.g. FreeSurfer's {'lh.orig' 'rh.orig'}, or
% Caret's {'X.L.Y.Z.surf.gii' 'X.R.Y.Z.surf.gii'}
% - a two-element cell-array points to files that represent
% the coordinates and topology in separate files, e.g.
% Caret's {'X.L.Y.Z.coord.gii' 'A.L.B.C.topo.gii'};
% By default all information from the two files will be concatenated (i.e. assumed to
% be the shape of left and right hemispeheres). The option 'concatenate' can be set
% to 'no' to prevent them from being concatenated in a single structure.
%
% Additional options should be specified in key-value pairs and can include
% 'format' = string, see below
% 'coordsys' = string, e.g. 'head' or 'dewar' (only supported for CTF)
% 'unit' = string, e.g. 'mm' (default is the native units of the file)
% 'concatenate' = 'no' or 'yes' (default = 'yes')
% 'image' = path to .jpg file
% 'surface' = specific surface to be read (only for caret spec files)
%
% Supported input file formats include
% 'matlab' containing FieldTrip or BrainStorm headshapes or cortical meshes
% 'stl' STereoLithography file format, for use with CAD and/or generic 3D mesh editing programs
% 'vtk' Visualization ToolKit file format, for use with Paraview
% 'vtk_xml' Visualization ToolKit file format
% 'tck' Mrtrix track file
% 'trk' Trackvis trk file
% 'mne_*' MNE surface description in ASCII format ('mne_tri') or MNE source grid in ascii format, described as 3D points ('mne_pos')
% 'obj' Wavefront .obj file obtained with the structure.io
% 'off'
% 'ply'
% 'itab_asc'
% 'ctf_*'
% '4d_*'
% 'neuromag_*'
% 'yokogawa_*'
% 'yorkinstruments_hdf5'
% 'polhemus_*'
% 'freesurfer_*'
% 'mne_source'
% 'spmeeg_mat'
% 'netmeg'
% 'vista'
% 'tet'
% 'tetgen_ele'
% 'gifti'
% 'caret_surf'
% 'caret_coord'
% 'caret_topo'
% 'caret_spec'
% 'brainvisa_mesh'
% 'brainsuite_dfs'
%
% See also FT_READ_HEADMODEL, FT_READ_SENS, FT_READ_ATLAS, FT_WRITE_HEADSHAPE
% Copyright (C) 2008-2019 Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
% get the options
annotationfile = ft_getopt(varargin, 'annotationfile');
useimage = ft_getopt(varargin, 'useimage', true); % use image if hasimage
concatenate = ft_getopt(varargin, 'concatenate', 'yes');
coordsys = ft_getopt(varargin, 'coordsys', 'head'); % for ctf or neuromag_mne coil positions, the alternative is dewar
fileformat = ft_getopt(varargin, 'format');
unit = ft_getopt(varargin, 'unit');
image = ft_getopt(varargin, 'image', [100, 100 ,100]); % path to .jpeg file
surface = ft_getopt(varargin, 'surface');
% Check the input, if filename is a cell-array, call ft_read_headshape recursively and combine the outputs.
% This is used to read the left and right hemisphere of a Freesurfer cortical segmentation.
if iscell(filename)
for i = 1:numel(filename)
tmp = ft_read_headshape(filename{i}, varargin{:});
haspos(i) = isfield(tmp, 'pos') && ~isempty(tmp.pos);
hastri(i) = isfield(tmp, 'tri') && ~isempty(tmp.tri);
if ~haspos(i), tmp.pos = []; end
if ~hastri(i), tmp.tri = []; end
if ~isfield(tmp, 'unit'), tmp.unit = 'unknown'; end
bnd(i) = tmp;
end
% Concatenate the bnds (only if 'concatenate' = 'yes' ) and if all
% structures have non-empty vertices and triangles. If not, the input filenames
% may have been caret-style coord and topo, which needs combination of
% the pos and tri.
if numel(filename)>1 && all(haspos==1) && strcmp(concatenate, 'yes')
if length(bnd)>2
ft_error('Cannot concatenate more than two files') % no more than two files are taken for cancatenation
else
fprintf('Concatenating the meshes in %s and %s\n', filename{1}, filename{2});
shape = [];
shape.pos = cat(1, bnd.pos);
npos = size(bnd(1).pos,1);
if isfield(bnd(1), 'tri') && isfield(bnd(2), 'tri')
shape.tri = cat(1, bnd(1).tri, bnd(2).tri + npos);
elseif ~isfield(bnd(1), 'tri') && ~isfield(bnd(2), 'tri')
% this is ok
else
ft_error('not all input files seem to contain a triangulation');
end
% concatenate any other fields
fnames = {'sulc' 'curv' 'area' 'thickness' 'atlasroi'};
for k = 1:numel(fnames)
if isfield(bnd(1), fnames{k}) && isfield(bnd(2), fnames{k})
shape.(fnames{k}) = cat(1, bnd.(fnames{k}));
elseif ~isfield(bnd(1), fnames{k}) && ~isfield(bnd(2), fnames{k})
% this is ok
else
ft_error('not all input files seem to contain a "%s"', fnames{k});
end
end
shape.brainstructure = []; % keeps track of the order of files in concatenation
for h = 1:length(bnd)
shape.brainstructure = [shape.brainstructure; h*ones(length(bnd(h).pos), 1)];
[p,f,e] = fileparts(filename{h});
% do an educated guess, otherwise default to the filename
iscortexright = ~isempty(strfind(f,'rh'));
iscortexright = iscortexright || ~isempty(strfind(f,'.R.'));
iscortexright = iscortexright || ~isempty(strfind(f,'Right'));
iscortexright = iscortexright || ~isempty(strfind(f,'RIGHT'));
iscortexleft = ~isempty(strfind(f,'lh'));
iscortexleft = iscortexleft || ~isempty(strfind(f,'.L.'));
iscortexleft = iscortexleft || ~isempty(strfind(f,'Left'));
iscortexleft = iscortexleft || ~isempty(strfind(f,'LEFT'));
if iscortexright && iscortexleft
% something strange is going on, default to the filename and let the user take care of this
shape.brainstructurelabel{h,1} = f;
elseif iscortexleft
shape.brainstructurelabel{h,1} = 'CORTEX_LEFT';
elseif iscortexright
shape.brainstructurelabel{h,1} = 'CORTEX_RIGHT';
else
% nothing to be guessed
shape.brainstructurelabel{h,1} = f;
end
end
end
elseif numel(filename)>1 && ~all(haspos==1)
if numel(bnd)>2
ft_error('Cannot combine more than two files') % no more than two files are taken for cancatenation
else
shape = [];
if sum(haspos==1)==1
fprintf('Using the vertex positions from %s\n', filename{find(haspos==1)});
shape.pos = bnd(haspos==1).pos;
shape.unit = bnd(haspos==1).unit;
else
ft_error('Don''t know what to do');
end
if sum(hastri==1)==1
fprintf('Using the faces definition from %s\n', filename{find(hastri==1)});
shape.tri = bnd(hastri==1).tri;
end
if max(shape.tri(:))~=size(shape.pos,1)
ft_error('mismatch in number of points in pos and tri');
end
end
else
% in case numel(filename)==1, or strcmp(concatenate, 'no')
shape = bnd;
end
return
end % if iscell
% checks if there exists a .jpg file of 'filename'
[pathstr,name] = fileparts(filename);
if useimage
if exist(fullfile(pathstr,[name,'.jpg']), 'file')
image = fullfile(pathstr,[name,'.jpg']);
hasimage = true;
elseif exist(fullfile(pathstr,[name,'.png']), 'file')
image = fullfile(pathstr,[name,'.png']);
hasimage = true;
else
hasimage = false;
end
else
hasimage = false;
end
% optionally get the data from the URL and make a temporary local copy
filename = fetch_url(filename);
if isempty(fileformat)
% only do the autodetection if the format was not specified
fileformat = ft_filetype(filename);
end
if ~isempty(annotationfile) && ~strcmp(fileformat, 'mne_source')
ft_error('at present extracting annotation information only works in conjunction with mne_source files');
end
% start with an empty structure
shape = [];
shape.pos = [];
switch fileformat
case {'ctf_ds', 'ctf_hc', 'ctf_meg4', 'ctf_res4', 'ctf_old'}
[p, f, x] = fileparts(filename);
if strcmp(fileformat, 'ctf_old')
fileformat = ft_filetype(filename);
end
if strcmp(fileformat, 'ctf_ds')
filename = fullfile(p, [f x], [f '.hc']);
elseif strcmp(fileformat, 'ctf_meg4')
filename = fullfile(p, [f '.hc']);
elseif strcmp(fileformat, 'ctf_res4')
filename = fullfile(p, [f '.hc']);
end
orig = read_ctf_hc(filename);
switch coordsys
case 'head'
shape.fid.pos = cell2mat(struct2cell(orig.head));
shape.coordsys = 'ctf';
case 'dewar'
shape.fid.pos = cell2mat(struct2cell(orig.dewar));
shape.coordsys = 'dewar';
otherwise
ft_error('incorrect coordsys specified');
end
shape.fid.label = fieldnames(orig.head);
case 'ctf_shape'
orig = read_ctf_shape(filename);
shape.pos = orig.pos;
% The file also contains fiducial information, but those are in MRI voxels and
% inconsistent with the headshape itself.
%
% shape.fid.label = {'NASION', 'LEFT_EAR', 'RIGHT_EAR'};
% shape.fid.pos = zeros(0,3); % start with an empty array
% for i = 1:numel(shape.fid.label)
% shape.fid.pos = cat(1, shape.fid.pos, getfield(orig.MRI_Info, shape.fid.label{i}));
% end
case {'4d_xyz', '4d_m4d', '4d_hs', '4d', '4d_pdf'}
[p, f, x] = fileparts(filename);
if ~strcmp(fileformat, '4d_hs')
filename = fullfile(p, 'hs_file');
end
[shape.pos, fid] = read_bti_hs(filename);
% I'm making some assumptions here
% which I'm not sure will work on all 4D systems
% fid = fid(1:3, :);
[junk, NZ] = max(fid(1:3,1));
[junk, L] = max(fid(1:3,2));
[junk, R] = min(fid(1:3,2));
rest = setdiff(1:size(fid,1),[NZ L R]);
shape.fid.pos = fid([NZ L R rest], :);
shape.fid.label = {'NZ', 'L', 'R'};
if ~isempty(rest),
for i = 4:size(fid,1)
shape.fid.label{i} = ['fiducial' num2str(i)];
% in a 5 coil configuration this corresponds with Cz and Inion
end
end
case 'itab_asc'
shape = read_itab_asc(filename);
case 'gifti'
ft_hastoolbox('gifti', 1);
g = gifti(filename);
if ~isfield(g, 'vertices')
ft_error('%s does not contain a tesselated surface', filename);
end
shape.pos = ft_warp_apply(g.mat, g.vertices);
shape.tri = g.faces;
shape.unit = 'mm'; % defined in the GIFTI standard to be milimeter
if isfield(g, 'cdata')
shape.mom = g.cdata;
end
case {'caret_surf' 'caret_topo' 'caret_coord'}
ft_hastoolbox('gifti', 1);
g = gifti(filename);
if ~isfield(g, 'vertices') && strcmp(fileformat, 'caret_topo')
try
% do a clever guess by replacing topo with coord
g2 = gifti(strrep(filename, '.topo.', '.coord.'));
vertices = ft_warp_apply(g2.mat, g2.vertices);
catch
vertices = [];
end
else
vertices = ft_warp_apply(g.mat, g.vertices);
end
if ~isfield(g, 'faces') && strcmp(fileformat, 'caret_coord')
try
% do a clever guess by replacing topo with coord
g2 = gifti(strrep(filename, '.coord.', '.topo.'));
faces = g2.faces;
catch
faces = [];
end
else
faces = g.faces;
end
shape.pos = vertices;
shape.tri = faces;
if isfield(g, 'cdata')
shape.mom = g.cdata;
end
% check whether there is curvature info etc
filename = strrep(filename, '.surf.', '.shape.');
filename = strrep(filename, '.topo.', '.shape.');
filename = strrep(filename, '.coord.', '.shape.');
[p,f,e] = fileparts(filename);
tok = tokenize(f, '.');
if length(tok)>2
tmpfilename = strrep(filename, tok{3}, 'sulc');
if exist(tmpfilename, 'file'), g = gifti(tmpfilename); shape.sulc = g.cdata; end
if exist(strrep(tmpfilename, 'sulc', 'curvature'), 'file'), g = gifti(strrep(tmpfilename, 'sulc', 'curvature')); shape.curv = g.cdata; end
if exist(strrep(tmpfilename, 'sulc', 'thickness'), 'file'), g = gifti(strrep(tmpfilename, 'sulc', 'thickness')); shape.thickness = g.cdata; end
if exist(strrep(tmpfilename, 'sulc', 'atlasroi'), 'file'), g = gifti(strrep(tmpfilename, 'sulc', 'atlasroi')); shape.atlasroi = g.cdata; end
end
case 'caret_spec'
[p, f, e] = fileparts(filename);
[spec, headerinfo] = read_caret_spec(filename);
fn = fieldnames(spec);
% concatenate the filenames that contain coordinates
% concatenate the filenames that contain topologies
coordfiles = {};
topofiles = {};
for k = 1:numel(fn)
if ~isempty(strfind(fn{k}, 'topo'))
topofiles = cat(1,topofiles, fullfile(p,spec.(fn{k})));
end
if ~isempty(strfind(fn{k}, 'coord'))
coordfiles = cat(1,coordfiles, fullfile(p,spec.(fn{k})));
end
end
if isempty(surface)
[selcoord, ok] = listdlg('ListString',coordfiles,'SelectionMode','single','PromptString','Select a file describing the coordinates');
else
selcoord = find(contains(coordfiles, surface));
end
if numel(topofiles)>1
[seltopo, ok] = listdlg('ListString',topofiles,'SelectionMode','single','PromptString','Select a file describing the topology');
else
seltopo = 1;
end
% recursively call ft_read_headshape
tmp1 = ft_read_headshape(coordfiles{selcoord});
tmp2 = ft_read_headshape(topofiles{seltopo});
% quick and dirty sanity check to see whether the indexing of the
% points in the topology matches the number of points
if max(tmp2.tri(:))~=size(tmp1.pos,1)
ft_error('there''s a mismatch between the number of points used in the topology, and described by the coordinates');
end
shape = tmp1;
shape.tri = tmp2.tri;
case 'neuromag_mex'
[co,ki,nu] = hpipoints(filename);
fid = co(:,find(ki==1))';
[junk, NZ] = max(fid(:,2));
[junk, L] = min(fid(:,1));
[junk, R] = max(fid(:,1));
shape.fid.pos = fid([NZ L R], :);
shape.fid.label = {'NZ', 'L', 'R'};
case 'mne_source'
% read the source space from an MNE file
ft_hastoolbox('mne', 1);
src = mne_read_source_spaces(filename, 1);
if ~isempty(annotationfile)
ft_hastoolbox('freesurfer', 1);
if numel(annotationfile)~=2
ft_error('two annotationfiles expected, one for each hemisphere');
end
for k = 1:numel(annotationfile)
[v{k}, label{k}, c(k)] = read_annotation(annotationfile{k}, 1);
end
% match the annotations with the src structures
if src(1).np == numel(label{1}) && src(2).np == numel(label{2})
src(1).labelindx = label{1};
src(2).labelindx = label{2};
elseif src(1).np == numel(label{2}) && src(1).np == numel(label{1})
src(1).labelindx = label{2};
src(2).labelindx = label{1};
else
ft_warning('incompatible annotation with triangulations, not using annotation information');
end
if ~isequal(c(1),c(2))
ft_error('the annotation tables differ, expecting equal tables for the hemispheres');
end
c = c(1);
end
shape = [];
% only keep the points that are in use
inuse1 = src(1).inuse==1;
inuse2 = src(2).inuse==1;
shape.pos=[src(1).rr(inuse1,:); src(2).rr(inuse2,:)];
% only keep the triangles that are in use; these have to be renumbered
newtri1 = src(1).use_tris;
newtri2 = src(2).use_tris;
for i=1:numel(src(1).vertno)
newtri1(newtri1==src(1).vertno(i)) = i;
end
for i=1:numel(src(2).vertno)
newtri2(newtri2==src(2).vertno(i)) = i;
end
shape.tri = [newtri1; newtri2 + numel(src(1).vertno)];
if isfield(src(1), 'use_tri_area')
shape.area = [src(1).use_tri_area(:); src(2).use_tri_area(:)];
end
if isfield(src(1), 'use_tri_nn')
shape.nn = [src(1).use_tri_nn; src(2).use_tri_nn];
end
shape.orig.pos = [src(1).rr; src(2).rr];
shape.orig.tri = [src(1).tris; src(2).tris + src(1).np];
shape.orig.inuse = [src(1).inuse src(2).inuse]';
shape.orig.nn = [src(1).nn; src(2).nn];
if isfield(src(1), 'labelindx')
shape.orig.labelindx = [src(1).labelindx;src(2).labelindx];
shape.labelindx = [src(1).labelindx(inuse1); src(2).labelindx(inuse2)];
% ulabelindx = unique(c.table(:,5));
% for k = 1:c.numEntries
% % the values are really high (apart from the 0), so I guess it's safe to start
% % numbering from 1
% shape.orig.labelindx(shape.orig.labelindx==ulabelindx(k)) = k;
% shape.labelindx(shape.labelindx==ulabelindx(k)) = k;
% end
% FIXME the above screws up the interpretation of the labels, because the color table is not sorted
shape.label = c.struct_names;
shape.annotation = c.orig_tab; % to be able to recover which one
shape.ctable = c.table;
end
case {'neuromag_fif' 'neuromag_mne'}
orig = read_neuromag_hc(filename);
switch coordsys
case 'head'
fidN=1;
posN=1;
for i=1:size(orig.head.pos,1)
if strcmp(orig.head.label{i}, 'LPA') || strcmp(orig.head.label{i}, 'Nasion') || strcmp(orig.head.label{i}, 'RPA')
shape.fid.pos(fidN,1:3) = orig.head.pos(i,:);
shape.fid.label{fidN} = orig.head.label{i};
fidN = fidN + 1;
else
shape.pos(posN,1:3) = orig.head.pos(i,:);
shape.label{posN} = orig.head.label{i};
posN = posN + 1;
end
end
shape.coordsys = orig.head.coordsys;
case 'dewar'
fidN=1;
posN=1;
for i=1:size(orig.dewar.pos,1)
if strcmp(orig.dewar.label{i}, 'LPA') || strcmp(orig.dewar.label{i}, 'Nasion') || strcmp(orig.dewar.label{i}, 'RPA')
shape.fid.pos(fidN,1:3) = orig.dewar.pos(i,:);
shape.fid.label{fidN} = orig.dewar.label{i};
fidN = fidN + 1;
else
shape.pos(posN,1:3) = orig.dewar.pos(i,:);
shape.label{posN} = orig.dewar.label{i};
posN = posN + 1;
end
end
shape.coordsys = orig.dewar.coordsys;
otherwise
ft_error('incorrect coordinates specified');
end
case {'ricoh_mrk', 'ricoh_ave', 'ricoh_con'}
hdr = read_ricoh_header(filename);
%% An exported file or an original one
isexported = hdr.orig.digitize.info.done;
%% Marker-coil positions
mrk_pnt = hdr.orig.coregist.hpi;
if any([mrk_pnt(:).meg_pos])
mrk_pos = cat(1, mrk_pnt(1:end).meg_pos);
mrk_label = transpose({mrk_pnt(1:end).label});
sw_ind = [3 1 2];
mrk_pos(1:3,:)= mrk_pos(sw_ind, :);
mrk_pos = mrk_pos * 100; % unit: cm
mrk_label(1:3,:)= mrk_label(sw_ind, :);
else
ft_error('No coil information found in the file');
end
%% Digitized points
if ~isexported
ft_info('The input file is an original one: only marker-coil positions are loaded\n');
% The fiducial points are represented by the marker-coil positions.
if any([mrk_pnt(:).meg_pos])
shape.fid.pos = mrk_pos; % unit: cm
shape.fid.label = {'nas'; 'lpa'; 'rpa'; 'Marker4'; 'Marker5'};
end
else
ft_info('The input file is a third-party-exported one including the digitized points\n');
% All digitized points
dig_pnt = hdr.orig.digitize.point;
digitizer2meg = hdr.orig.digitize.info.digitizer2meg;
R = digitizer2meg(1:3,1:3);
T = digitizer2meg(1:3,4);
% Transform to MEG coordinate:
shape.pos = transpose( R * [[dig_pnt.x]; [dig_pnt.y]; [dig_pnt.z]] + repmat(T, 1, numel(dig_pnt))).*100; % unit: cm
shape.label = transpose( deblank({dig_pnt(1:end).name}));
% Fiducial points
nas = find(strcmpi(shape.label, 'fidnz'));
lpa = find(strcmpi(shape.label, 'fidt9'));
rpa = find(strcmpi(shape.label, 'fidt10'));
if ~isempty(nas) && ~isempty(lpa) && ~isempty(rpa)
anatfid_pos = [ shape.pos(nas,:) ; shape.pos(lpa,:) ; shape.pos(rpa,:) ];
anatfid_label = {'nas'; 'lpa'; 'rpa'};
end
% HPIs
HPI_1 = find(strcmpi(shape.label, 'HPI_1'));
HPI_2 = find(strcmpi(shape.label, 'HPI_2'));
HPI_3 = find(strcmpi(shape.label, 'HPI_3'));
HPI_4 = find(strcmpi(shape.label, 'HPI_4'));
HPI_5 = find(strcmpi(shape.label, 'HPI_5'));
if ~isempty(HPI_1) && ~isempty(HPI_2) && ~isempty(HPI_3) && ~isempty(HPI_4) && ~isempty(HPI_5)
HPI_pos = [ shape.pos(HPI_3,:) ;...
shape.pos(HPI_1,:) ;...
shape.pos(HPI_2,:) ;...
shape.pos(HPI_4,:) ;...
shape.pos(HPI_5,:) ];
HPI_label = { 'HPI_3'; 'HPI_1'; 'HPI_2'; 'HPI_4'; 'HPI_5' };
end
shape.fid.pos = [ anatfid_pos; HPI_pos; mrk_pos ];
shape.fid.label = [ anatfid_label; HPI_label; mrk_label ];
end
% 'cm' as a unit for 'pos':
shape.unit = 'cm';
case {'yokogawa_mrk', 'yokogawa_ave', 'yokogawa_con'}
if ft_hastoolbox('yokogawa_meg_reader')
hdr = read_yokogawa_header_new(filename);
%% Marker-coil positions
mrk_pnt = hdr.orig.coregist.hpi;
% markers 1-3 identical to zero: try *.mrk file
if ~any([mrk_pnt(:).meg_pos])
ft_info('Reading marker-coil positions from a .mrk file\n');
[p, f, x] = fileparts(filename);
filename = fullfile(p, [f '.mrk']);
if exist(filename, 'file')
hdr_tmp = read_yokogawa_header_new(filename);
mrk_pnt = hdr_tmp.orig.coregist.hpi;
end
end
if any([mrk_pnt(:).meg_pos])
mrk_pos = cat(1, mrk_pnt(1:end).meg_pos);
mrk_label = transpose({mrk_pnt(1:end).label});
sw_ind = [3 1 2];
mrk_pos(1:3,:)= mrk_pos(sw_ind, :);
mrk_pos = mrk_pos * 100; % unit: cm
mrk_label(1:3,:)= mrk_label(sw_ind, :);
else
ft_error('No coil information found in the file');
end
%% An exported file or an original one
isexported = hdr.orig.digitize.info.done;
%% Digitized points
if ~isexported
ft_info('The input file is an original one: only marker-coil positions are loaded\n');
% The fiducial points are represented by the marker-coil positions.
if any([mrk_pnt(:).meg_pos])
shape.fid.pos = mrk_pos; % unit: cm
shape.fid.label = {'nas'; 'lpa'; 'rpa'; 'Marker4'; 'Marker5'};
end
else
ft_info('The input file is a third-party-exported one including the digitized points\n');
% All digitized points
dig_pnt = hdr.orig.digitize.point;
digitizer2meg = hdr.orig.digitize.info.digitizer2meg;
R = digitizer2meg(1:3,1:3);
T = digitizer2meg(1:3,4);
% Transform to MEG coordinate:
shape.pos = transpose( R * [[dig_pnt.x]; [dig_pnt.y]; [dig_pnt.z]] + repmat(T, 1, numel(dig_pnt))).*100; % unit: cm
shape.label = transpose( deblank({dig_pnt(1:end).name}));
% Fiducial points
nas = find(strcmpi(shape.label, 'fidnz'));
lpa = find(strcmpi(shape.label, 'fidt9'));
rpa = find(strcmpi(shape.label, 'fidt10'));
if ~isempty(nas) && ~isempty(lpa) && ~isempty(rpa)
anatfid_pos = [ shape.pos(nas,:) ; shape.pos(lpa,:) ; shape.pos(rpa,:) ];
anatfid_label = {'nas'; 'lpa'; 'rpa'};
end
% HPIs
HPI_1 = find(strcmpi(shape.label, 'HPI_1'));
HPI_2 = find(strcmpi(shape.label, 'HPI_2'));
HPI_3 = find(strcmpi(shape.label, 'HPI_3'));
HPI_4 = find(strcmpi(shape.label, 'HPI_4'));
HPI_5 = find(strcmpi(shape.label, 'HPI_5'));
if ~isempty(HPI_1) && ~isempty(HPI_2) && ~isempty(HPI_3) && ~isempty(HPI_4) && ~isempty(HPI_5)
HPI_pos = [ shape.pos(HPI_3,:) ;...
shape.pos(HPI_1,:) ;...
shape.pos(HPI_2,:) ;...
shape.pos(HPI_4,:) ;...
shape.pos(HPI_5,:) ];
HPI_label = { 'HPI_3'; 'HPI_1'; 'HPI_2'; 'HPI_4'; 'HPI_5' };
end
shape.fid.pos = [ anatfid_pos; HPI_pos; mrk_pos ];
shape.fid.label = [ anatfid_label; HPI_label; mrk_label ];
end
% 'cm' as a unit for 'pos':
shape.unit = 'cm';
else % the case that "yokogawa_meg_reader" is not available
hdr = read_yokogawa_header(filename);
marker = hdr.orig.matching_info.marker;
% markers 1-3 identical to zero: try *.mrk file
if ~any([marker(:).meg_pos])
[p, f, x] = fileparts(filename);
filename = fullfile(p, [f '.mrk']);
if exist(filename, 'file')
hdr = read_yokogawa_header(filename);
marker = hdr.orig.matching_info.marker;
end
end
% non zero markers 1-3
if any([marker(:).meg_pos])
shape.fid.pos = cat(1, marker(1:5).meg_pos);
sw_ind = [3 1 2];
shape.fid.pos(1:3,:)= shape.fid.pos(sw_ind, :);
shape.fid.label = {'nas'; 'lpa'; 'rpa'; 'Marker4'; 'Marker5'};
else
ft_error('no coil information found in Yokogawa file');
end
% convert to the units of the grad, the desired default for yokogawa is centimeter.
shape = ft_convert_units(shape, 'cm');
end
case 'yokogawa_raw'
if ft_hastoolbox('yokogawa_meg_reader')
hdr = read_yokogawa_header_new(filename);
marker = hdr.orig.coregist.hpi;
else
hdr = read_yokogawa_header(filename);
marker = hdr.orig.matching_info.marker;
end
% markers 1-3 identical to zero: try *.mrk file
if ~any([marker(:).meg_pos])
[p, f, x] = fileparts(filename);
filename = fullfile(p, [f '.mrk']);
if exist(filename, 'file')
if ft_hastoolbox('yokogawa_meg_reader')
hdr = read_yokogawa_header_new(filename);
marker = hdr.orig.coregist.hpi;
else
hdr = read_yokogawa_header(filename);
marker = hdr.orig.matching_info.marker;
end
end
end
% non zero markers 1-3
if any([marker(:).meg_pos])
shape.fid.pos = cat(1, marker(1:5).meg_pos);
sw_ind = [3 1 2];
shape.fid.pos(1:3,:)= shape.fid.pos(sw_ind, :);
shape.fid.label = {'nas'; 'lpa'; 'rpa'; 'Marker4'; 'Marker5'};
else
ft_error('no coil information found in Yokogawa file');
end
% convert to the units of the grad, the desired default for yokogawa is centimeter.
shape = ft_convert_units(shape, 'cm');
% case {'yokogawa_mrk', 'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw' }
% if ft_hastoolbox('yokogawa_meg_reader')
% hdr = read_yokogawa_header_new(filename);
% marker = hdr.orig.coregist.hpi;
% else
% hdr = read_yokogawa_header(filename);
% marker = hdr.orig.matching_info.marker;
% end
%
% % markers 1-3 identical to zero: try *.mrk file
% if ~any([marker(:).meg_pos])
% [p, f, x] = fileparts(filename);
% filename = fullfile(p, [f '.mrk']);
% if exist(filename, 'file')
% if ft_hastoolbox('yokogawa_meg_reader')
% hdr = read_yokogawa_header_new(filename);
% marker = hdr.orig.coregist.hpi;
% else
% hdr = read_yokogawa_header(filename);
% marker = hdr.orig.matching_info.marker;
% end
% end
% end
%
% % non zero markers 1-3
% if any([marker(:).meg_pos])
% shape.fid.pos = cat(1, marker(1:5).meg_pos);
% sw_ind = [3 1 2];
% shape.fid.pos(1:3,:)= shape.fid.pos(sw_ind, :);
% shape.fid.label = {'nas'; 'lpa'; 'rpa'; 'Marker4'; 'Marker5'};
% else
% ft_error('no coil information found in Yokogawa file');
% end
%
% % convert to the units of the grad, the desired default for yokogawa is centimeter.
% shape = ft_convert_units(shape, 'cm');
case 'yokogawa_coregis'
in_str = textread(filename, '%s');
nr_items = size(in_str,1);
ind = 1;
coil_ind = 1;
shape.fid.pos = [];
shape.fid.label = {};
while ind < nr_items
if strcmp(in_str{ind},'MEG:x=')
shape.fid.pos = [shape.fid.pos; str2num(strtok(in_str{ind+1},[',','['])) ...
str2num(strtok(in_str{ind+3},[',','['])) str2num(strtok(in_str{ind+5},[',','[']))];
shape.fid.label = [shape.fid.label ; ['Marker',num2str(coil_ind)]];
coil_ind = coil_ind + 1;
ind = ind + 6;
else
ind = ind +1;
end
end
if size(shape.fid.label,1) ~= 5
ft_error('Wrong number of coils');
end
sw_ind = [3 1 2];
shape.fid.pos(1:3,:)= shape.fid.pos(sw_ind, :);
shape.fid.label(1:3)= {'nas', 'lpa', 'rpa'};
case 'yokogawa_hsp'
fid = fopen_or_error(filename, 'rt');
fidstart = false;
hspstart = false;
% try to locate the fiducial positions
while ~fidstart && ~feof(fid)
line = fgetl(fid);
if ~isempty(strmatch('//Position of fiducials', line))
fidstart = true;
end
end
if fidstart
line_xpos = fgetl(fid);
line_ypos = fgetl(fid);
line_yneg = fgetl(fid);
xpos = sscanf(line_xpos(3:end), '%f');
ypos = sscanf(line_ypos(3:end), '%f');
yneg = sscanf(line_yneg(3:end), '%f');
shape.fid.pos = [
xpos(:)'
ypos(:)'
yneg(:)'
];
shape.fid.label = {
'X+'
'Y+'
'Y-'
};
end
% try to locate the fiducial positions
while ~hspstart && ~feof(fid)
line = fgetl(fid);
if ~isempty(strmatch('//No of rows', line))
hspstart = true;
end
end
if hspstart
line = fgetl(fid);
siz = sscanf(line, '%f');
shape.pos = zeros(siz(:)');
for i=1:siz(1)
line = fgetl(fid);
shape.pos(i,:) = sscanf(line, '%f');
end
end
fclose(fid);
case 'yorkinstruments_hdf5'
acquisition='default';
try
shape.pos=transpose(h5read(filename, '/geometry/head_shape/head_shape'));
catch
error('Headshape data not found.');
end
shape.unit='mm';
temp=h5info(filename, '/geometry/fiducials/');
Nfids=length(temp.Groups);
for i=1:Nfids
[null, shape.fid.label{i}, null]= fileparts(temp.Groups(i).Name);
shape.fid.pos(i,1:3)=h5read(filename, strcat('/geometry/fiducials/',shape.fid.label{i} ,'/location'));
end
if isempty(coordsys)
coordsys='dewar'
end
if strcmp(coordsys,'dewar')
try
tCCStoMegscanScs = h5read(filename,[strcat('/acquisitions/',char(string(acquisition))) '/ccs_to_scs_transform']);
T = maketform('affine',tCCStoMegscanScs);
shape.pos=tforminv(T,shape.pos(:,1),shape.pos(:,2),shape.pos(:,3));
shape.fid.pos=tforminv(T,shape.fid.pos(:,1),shape.fid.pos(:,2),shape.fid.pos(:,3));
catch
error('No head to dewar transform available in hdf5 file');
end
end
case 'ply'
[vert, face] = read_ply(filename);
shape.pos = [vert.x vert.y vert.z];
if isfield(vert, 'red') && isfield(vert, 'green') && isfield(vert, 'blue')
shape.color = double([vert.red vert.green vert.blue])/255;
end
switch size(face,2)
case 3
shape.tri = face;
case 4
shape.tet = face;
case 8
shape.hex = face;
end
case 'polhemus_fil'
[shape.fid.pos, shape.pos, shape.fid.label] = read_polhemus_fil(filename, 0);
case 'polhemus_pos'
[shape.fid.pos, shape.pos, shape.fid.label] = read_ctf_pos(filename);
case 'spmeeg_mat'
tmp = load(filename);
if isfield(tmp.D, 'fiducials') && ~isempty(tmp.D.fiducials)
shape = tmp.D.fiducials;
else
ft_error('no headshape found in SPM EEG file');
end
case 'matlab'
% determine which variables are contained in the file
tmp = load(filename);
if isfield(tmp, 'shape')
shape = tmp.shape;
elseif isfield(tmp, 'headshape')
shape = tmp.headshape;
elseif isfield(tmp, 'surface')
shape = tmp.surface;
elseif isfield(tmp, 'bnd')
% the variable in the file is most likely a precomputed triangulation of some sort
shape = tmp.bnd;
elseif isfield(tmp, 'mesh')
% the variable in the file is most likely a precomputed triangulation of some sort
shape = tmp.mesh;
elseif isfield(tmp, 'elec')
% represent the electrodes as headshape
tmp.elec = ft_datatype_sens(tmp.elec);
shape.fid.pos = tmp.elec.chanpos;
shape.fid.label = tmp.elec.label;
elseif isfield(tmp, 'Vertices')
% this applies to BrainStorm cortical meshes
shape.pos = tmp.Vertices;
% copy some optional fields over with a new name
shape = copyfields(tmp, shape, {'Faces', 'Curvature', 'SulciMap'});
shape = renamefields(shape, {'Faces', 'Curvature', 'SulciMap'}, {'tri', 'curv', 'sulc'});
elseif numel(fieldnames(tmp))==1
fn = fieldnames(tmp);
shape = tmp.(fn{1});
% check that it has vertices and triangles
assert(isfield(shape, 'pos') && isfield(shape, 'tri'), 'no headshape found in MATLAB file')
else
ft_error('no headshape found in MATLAB file');
end
case {'freesurfer_triangle_binary', 'freesurfer_quadrangle'}
% the freesurfer toolbox is required for this
ft_hastoolbox('freesurfer', 1);
[pos, tri] = read_surf(filename);
if min(tri(:)) == 0
% start counting from 1
tri = tri + 1;
end
shape.pos = pos;
shape.tri = tri;
% for the left and right
[path,name,ext] = fileparts(filename);
if strcmp(ext, '.inflated') % does the shift only for inflated surface
if strcmp(name, 'lh')
% assume freesurfer inflated mesh in mm, mni space
% move the mesh a bit to the left, to avoid overlap with the right
% hemisphere
shape.pos(:,1) = shape.pos(:,1) - max(shape.pos(:,1)) - 10;
elseif strcmp(name, 'rh')
% id.
% move the mesh a bit to the right, to avoid overlap with the left
% hemisphere
shape.pos(:,1) = shape.pos(:,1) - min(shape.pos(:,1)) + 10;
end
end
if exist(fullfile(path, [name,'.sulc']), 'file'), shape.sulc = read_curv(fullfile(path, [name,'.sulc'])); end
if exist(fullfile(path, [name,'.curv']), 'file'), shape.curv = read_curv(fullfile(path, [name,'.curv'])); end
if exist(fullfile(path, [name,'.area']), 'file'), shape.area = read_curv(fullfile(path, [name,'.area'])); end
if exist(fullfile(path, [name,'.thickness']), 'file'), shape.thickness = read_curv(fullfile(path, [name,'.thickness'])); end
case 'stl'
[pos, tri, nrm] = read_stl(filename);
shape.pos = pos;
shape.tri = tri;
case 'obj'
ft_hastoolbox('wavefront', 1);
% Only tested for structure.io .obj thus far
[pos, tri, texture, textureIdx] = read_obj_new(filename);
% check if the texture is defined per vertex, in which case the texture can be refined below
if size(texture, 1)==size(pos, 1)
texture_per_vert = true;
else
texture_per_vert = false;
end
% remove the triangles with 0's first
allzeros = sum(tri==0,2)==3;
tri(allzeros, :) = [];
textureIdx(allzeros, :) = [];