/
ft_prepare_layout.m
1842 lines (1661 loc) · 103 KB
/
ft_prepare_layout.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 [layout, cfg] = ft_prepare_layout(cfg, data)
% FT_PREPARE_LAYOUT loads or creates a 2-D layout of the channel locations. This
% layout is required for plotting the topographical distribution of the potential or
% field distribution, or for plotting timecourses in a topographical arrangement.
%
% Use as
% layout = ft_prepare_layout(cfg)
% or
% layout = ft_prepare_layout(cfg, data)
% where the optional data input argument is any of the FieldTrip data structures.
%
% This returns a layout structure with the following elements
% layout.pos = Nx2 matrix with the position where each channel should be plotted
% layout.label = Nx1 cell-array with the channel labels
% layout.width = Nx1 vector with the width of each box for multiplotting
% layout.height = Nx1 vector with the height of each box for multiplotting
% layout.mask = optional cell-array with line segments that determine the area for topographic interpolation
% layout.outline = optional cell-array with line segments that represent the head, nose, ears, sulci or other anatomical features
% layout.color = optional Nx3 matrix with rgb values for the channels' color, for fine-grained color behavior
%
% There are several ways in which a 2-D layout can be made:
% 1) it can be read directly from a layout file
% 2) it can be created on basis of an image or photo,
% 3) it can be created from a projection of the 3-D sensor positions in the data, in the configuration, or in an electrode, gradiometer or optode file.
%
% Layout files are MATLAB *.mat files containing a single structure representing the layout
% (see above). The layout file can also be an ASCII file with the extension *.lay, although
% this file format is no longer recommended, since there is less control over the outline
% of the head and the mask within which the interpolation is done. A large number of
% template layout files is provided in the fieldtrip/template/layout directory. See
% also http://www.fieldtriptoolbox.org/template/layout
%
% You can specify any one of the following configuration options
% cfg.layout = filename containg the input layout (*.mat or *.lay file), this can also be a layout
% structure, which is simply returned as-is (see below for details)
% cfg.output = filename (ending in .mat or .lay) to which the layout will be written (default = [])
% cfg.feedback = 'yes' or 'no', whether to show an image of the layout (default = 'no')
% cfg.elec = structure with electrode positions or filename, see FT_READ_SENS
% cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS
% cfg.opto = structure with optode definition or filename, see FT_READ_SENS
% cfg.rotate = number, rotation around the z-axis in degrees (default = [], which means automatic)
% cfg.center = string, center and scale the electrodes in the sphere that represents the head, can be 'yes' or 'no' (default = 'no')
% cfg.projection = string, 2D projection method can be 'stereographic', 'orthographic', 'polar' or 'gnomic' (default = 'polar')
% When 'orthographic', cfg.viewpoint can be used to indicate to specificy projection (keep empty for legacy projection)
% cfg.viewpoint = string indicating the view point that is used for orthographic projection of 3-D sensor
% positions to the 2-D plane. The possible viewpoints are
% 'left' - left sagittal view, L=anterior, R=posterior, top=top, bottom=bottom
% 'right' - right sagittal view, L=posterior, R=anterior, top=top, bottom=bottom
% 'topleft' - view from the top top, L=anterior, R=posterior, top=top, bottom=bottom
% 'topright' - view from the top right, L=posterior, R=anterior, top=top, bottom=bottom
% 'inferior' - inferior axial view, L=R, R=L, top=anterior, bottom=posterior
% 'superior' - superior axial view, L=L, R=R, top=anterior, bottom=posterior
% 'anterior' - anterior coronal view, L=R, R=L, top=top, bottom=bottom
% 'posterior' - posterior coronal view, L=L, R=R, top=top, bottom=bottom
% 'auto' - automatic guess of the most optimal of the above
% tip: use cfg.viewpoint = 'auto' per iEEG electrode grid/strip/depth for more accurate results
% tip: to obtain an overview of all iEEG electrodes, choose superior/inferior, use cfg.headshape/mri, and plot using FT_LAYOUTPLOT with cfg.box/mask = 'no'
% cfg.outline = string, how to create the outline, can be 'circle', 'doublecirclecross', 'helmet', 'square', 'convex', 'headshape', 'mri' or 'no' (default is automatic)
% cfg.mask = string, how to create the mask, can be 'circle', 'extended', 'square', 'convex', 'headshape', 'mri' or 'no' (default is automatic)
% cfg.headshape = surface mesh (for example pial or head) to be used for generating an outline, see FT_READ_HEADSHAPE for details
% cfg.mri = segmented anatomical MRI to be used for generating an outline, see FT_READ_MRI and FT_VOLUMESEGMENT for details
% cfg.montage = 'no' or a montage structure (default = 'no')
% cfg.image = filename, use an image to construct a layout (useful for ECoG grids)
% cfg.bw = 'yes' or 'no', if an image is used and this option is true, the image is transformed in black and white (default = 'no', i.e. do not transform)
% cfg.overlap = string, how to deal with overlapping channels when the layout is constructed from a sensor configuration structure. This can be
% 'shift' - shift the positions in 2D space to remove the overlap (default)
% 'keep' - do not shift, retain the overlap
% 'no' - throw an error when overlap is present
% cfg.channel = 'all', or Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details
% cfg.boxchannel = 'all', or Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details
% specificies channels to use for determining channel box size (default = 'all', recommended for MEG/EEG, a selection is recommended for iEEG)
% cfg.skipscale = 'yes' or 'no', whether the scale should be included in the layout or not (default = 'no')
% cfg.skipcomnt = 'yes' or 'no', whether the comment should be included in the layout or not (default = 'no')
% cfg.color = empty, 'spatial', or Nx3 matrix, if non-empty, an Nx3 color matrix based on the position
% of the sensors will be added (default = [])
%
% If you use cfg.headshape or cfg.mri to create a headshape outline, the input
% geometry should be expressed in the same units and coordinate system as the input
% sensors.
%
% Alternatively the layout can be constructed from either one of these in the input data structure:
% data.elec = structure with electrode positions
% data.grad = structure with gradiometer definition
% data.opto = structure with optode definition
%
% Alternatively you can specify the following options for systematic layouts which
% will be generated for all channels present in the data. Note that these layouts are
% only suitable for multiplotting, not for topoplotting.
% cfg.layout = 'ordered' will give you a NxN ordered layout
% cfg.layout = 'vertical' will give you a Nx1 ordered layout
% cfg.layout = 'horizontal' will give you a 1xN ordered layout
% cfg.layout = 'butterfly' will give you a layout with all channels on top of each other
% cfg.layout = 'circular' will distribute the channels on a circle
% cfg.width = scalar (default is automatic)
% cfg.height = scalar (default is automatic)
%
% For an sEEG shaft the option cfg.layout='vertical' or 'horizontal' is useful to
% represent the channels in a linear sequence . In this case you can also specify the
% direction of the shaft as going from left-to-right, top-to-bottom, etc.
% cfg.direction = string, can be any of 'LR', 'RL' (for horizontal), 'TB', 'BT' (for vertical)
%
% For an ECoG grid the option cfg.layout='ordered' is useful to represent the
% channels in a grid array. In this case you can also specify the number of rows
% and/or columns and hwo the channels increment over the grid (e.g. first
% left-to-right, then top-to-bottom). You can check the channel order of your grid
% using FT_PLOT_LAYOUT.
% cfg.rows = number of rows (default is automatic)
% cfg.columns = number of columns (default is automatic)
% cfg.direction = string, can be any of 'LRTB', 'RLTB', 'LRBT', 'RLBT', 'TBLR', 'TBRL', 'BTLR', 'BTRL' (default = 'LRTB')
%
% See also FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_PLOT_LAYOUT
% undocumented and non-recommended option (for SPM only)
% cfg.style string, '2d' or '3d' (default = '2d')
% Copyright (C) 2007-2020, 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$
% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin = nargin;
ft_nargout = nargout;
% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble loadvar data
ft_preamble provenance data
% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
return
end
% the data can be passed as input argument or can be read from disk
hasdata = exist('data', 'var') && ~isempty(data);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% basic check/initialization of input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~hasdata
data = struct([]);
else
% check if the input data is valid for this function
data = ft_checkdata(data);
end
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'forbidden', {'channels'}); % prevent accidental typos, see issue 1729
cfg = ft_checkconfig(cfg, 'renamed', {'elecfile', 'elec'});
cfg = ft_checkconfig(cfg, 'renamed', {'gradfile', 'grad'});
cfg = ft_checkconfig(cfg, 'renamed', {'optofile', 'opto'});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set default configuration options
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cfg.rotate = ft_getopt(cfg, 'rotate', []); % [] => default rotation is determined based on the type of sensors
cfg.center = ft_getopt(cfg, 'center', 'no');
cfg.style = ft_getopt(cfg, 'style', '2d');
cfg.projection = ft_getopt(cfg, 'projection', 'polar');
cfg.layout = ft_getopt(cfg, 'layout', []);
cfg.grad = ft_getopt(cfg, 'grad', []);
cfg.elec = ft_getopt(cfg, 'elec', []);
cfg.opto = ft_getopt(cfg, 'opto', []);
cfg.output = ft_getopt(cfg, 'output', []);
cfg.feedback = ft_getopt(cfg, 'feedback', 'no');
cfg.montage = ft_getopt(cfg, 'montage', 'no');
cfg.image = ft_getopt(cfg, 'image', []);
cfg.mesh = ft_getopt(cfg, 'mesh', []); % experimental, should only work with meshes defined in 2D
cfg.bw = ft_getopt(cfg, 'bw', 'no');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.skipscale = ft_getopt(cfg, 'skipscale', []); % see below
cfg.skipcomnt = ft_getopt(cfg, 'skipcomnt', []); % see below
cfg.boxchannel = ft_getopt(cfg, 'boxchannel', cfg.channel);
cfg.overlap = ft_getopt(cfg, 'overlap', 'shift');
cfg.viewpoint = ft_getopt(cfg, 'viewpoint', []);
cfg.headshape = ft_getopt(cfg, 'headshape', []); % separate form cfg.mesh
cfg.mri = ft_getopt(cfg, 'mri', []);
cfg.outline = ft_getopt(cfg, 'outline', []); % default is handled below
cfg.mask = ft_getopt(cfg, 'mask', []); % default is handled below
cfg.width = ft_getopt(cfg, 'width', []);
cfg.height = ft_getopt(cfg, 'height', []);
cfg.commentpos = ft_getopt(cfg, 'commentpos', 'layout');
cfg.scalepos = ft_getopt(cfg, 'scalepos', 'layout');
cfg.color = ft_getopt(cfg, 'color', []);
if isempty(cfg.skipscale)
if ischar(cfg.layout) && any(strcmp(cfg.layout, {'ordered', 'vertical', 'horizontal', 'butterfly', 'circular'}))
cfg.skipscale = 'yes';
else
cfg.skipscale = 'no';
end
end
if isempty(cfg.skipcomnt)
if ischar(cfg.layout) && any(strcmp(cfg.layout, {'ordered', 'vertical', 'horizontal', 'butterfly', 'circular'}))
cfg.skipcomnt = 'yes';
else
cfg.skipcomnt = 'no';
end
end
if isempty(cfg.outline) || strcmp(cfg.outline, 'yes')
% determine the most suitable shape of the outline
if ~isempty(cfg.headshape)
cfg.outline = 'headshape';
elseif ~isempty(cfg.mri)
cfg.outline = 'mri';
elseif ischar(cfg.layout) && any(strcmp(cfg.layout, {'horizontal', 'vertical', 'ordered'}))
cfg.outline = 'no';
elseif ~strcmp(cfg.projection, 'orthographic')
cfg.outline = 'circle';
else
cfg.outline = 'no';
end
end
if isempty(cfg.mask) || strcmp(cfg.mask, 'yes')
% determine the most suitable shape of the mask
if ~isempty(cfg.headshape)
cfg.mask = 'headshape';
elseif ~isempty(cfg.mri)
cfg.mask = 'mri';
elseif ischar(cfg.layout) && any(strcmp(cfg.layout, {'horizontal', 'vertical', 'ordered'}))
cfg.mask = 'square';
elseif ~strcmp(cfg.projection, 'orthographic')
cfg.mask = 'circle';
else
cfg.mask = 'convex';
end
end
% headshape/mri are mutually exclusive
if ~isempty(cfg.headshape) && ~isempty(cfg.mri)
ft_error('cfg.headshape and cfg.mri are mutually exclusive, please use only one of the two')
end
% cfg.viewpoint can only be used together with cfg.projection = 'orthographic'
if ~isempty(cfg.viewpoint) && ~isequal(cfg.projection, 'orthographic')
ft_error('cfg.viewpoint can only be used in the case of orthographic projection')
end
if ~isempty(cfg.viewpoint) && ~isempty(cfg.rotate)
ft_error('cfg.viewpoint and cfg.rotate are mutually exclusive, please use only one of the two')
end
% update the selection of channels according to the data
if hasdata && isfield(data, 'topolabel')
cfg.channel = ft_channelselection(cfg.channel, data.topolabel);
elseif hasdata && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif hasdata && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
if ischar(cfg.layout) && strcmp(cfg.layout, 'vertical')
cfg.direction = ft_getopt(cfg, 'direction', 'TB'); % default is top-to-bottom
elseif ischar(cfg.layout) && strcmp(cfg.layout, 'horizontal')
cfg.direction = ft_getopt(cfg, 'direction', 'LR'); % default is left-to-right
elseif ischar(cfg.layout) && strcmp(cfg.layout, 'ordered')
cfg.direction = ft_getopt(cfg, 'direction', 'LRTB'); % default is left-to-right, then top-to-bottom
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to generate the layout structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
skipscale = istrue(cfg.skipscale); % in general a scale is desired
skipcomnt = istrue(cfg.skipcomnt); % in general a comment desired
% ensure that there is a label field in the data, which is needed for
% ordered/vertical//horizontal/butterfly modes
if hasdata && ~isfield(data, 'label') && isfield(data, 'labelcmb')
data.label = unique(data.labelcmb(:));
end
% check whether cfg.layout already contains a valid layout structure (this can
% happen when higher level plotting functions are called with cfg.layout set to
% a layout structure)
if isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && isfield(cfg.layout, 'width') && isfield(cfg.layout, 'height')
layout = cfg.layout;
elseif isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && (~isfield(cfg.layout, 'width') || ~isfield(cfg.layout, 'height'))
layout = cfg.layout;
% add width and height for multiplotting
d = dist(layout.pos');
nchans = length(layout.label);
for i=1:nchans
d(i,i) = inf; % exclude the diagonal
end
mindist = min(d(:));
layout.width = ones(nchans,1) * mindist * 0.8;
layout.height = ones(nchans,1) * mindist * 0.6;
elseif isequal(cfg.layout, 'circular')
rho = ft_getopt(cfg, 'rho', []);
if hasdata && ~isempty(data)
% look at the data to determine the overlapping channels
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
nchan = length(data.label(chanindx));
layout.label = data.label(chanindx);
else
assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels');
nchan = length(cfg.channel);
layout.label = cfg.channel;
end
if isempty(rho)
% do an equally spaced layout, starting at 12 o'clock, going clockwise
rho = linspace(0,1,nchan+1);
rho = 2.*pi.*rho(1:end-1);
else
if numel(rho) ~= nchan
ft_error('the number of elements in the polar angle vector should be equal to the number of channels');
end
% convert to radians
rho = 2.*pi.*rho./360;
end
x = sin(rho);
y = cos(rho);
layout.pos = [x(:) y(:)];
layout.width = ones(nchan,1) * 0.01;
layout.height = ones(nchan,1) * 0.01;
layout.mask = {};
layout.outline = {};
elseif isequal(cfg.layout, 'butterfly')
if hasdata && ~isempty(data)
% look at the data to determine the channels to be plotted
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
nchan = length(data.label(chanindx));
layout.label = data.label(chanindx);
else
assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels');
nchan = length(cfg.channel);
layout.label = cfg.channel;
end
layout.pos = zeros(nchan,2); % centered at (0,0)
layout.width = ones(nchan,1) * 1.0;
layout.height = ones(nchan,1) * 1.0;
layout.mask = {};
layout.outline = {};
if ~istrue(cfg.skipscale)
layout.label{end+1} = 'SCALE';
layout.pos(end+1, :) = layout.pos(1,:);
layout.width(end+1) = layout.width(1);
layout.height(end+1) = layout.height(1);
end
if strcmp(cfg.color, 'spatial')
try
% make one with the default settings to copy the spatial colors
tmpcfg = keepfields(cfg, {'channel', 'color', 'skipcomnt', 'skipscale'});
tmpcfg = ft_setopt(tmpcfg, 'showcallinfo', 'no');
tmpcfg = ft_setopt(tmpcfg, 'trackcallinfo', 'no');
tmplayout = ft_prepare_layout(tmpcfg, data);
layout.color = tmplayout.color;
catch
% it will fail if the data does not contain grad or elec
ft_warning('cannot determine spatial colors');
end
end
elseif isequal(cfg.layout, 'vertical') || isequal(cfg.layout, 'horizontal')
assert(iscell(cfg.channel), 'cfg.channel should be a cell-array of strings');
nchan = length(cfg.channel);
layout.label = cfg.channel;
% the width and height of the box are as specified
% the distance between the channels is slightly larger
switch cfg.layout
case 'vertical'
cfg.width = ft_getopt(cfg, 'width', 0.8);
cfg.height = ft_getopt(cfg, 'height', 0.8 * 1/(nchan+1+2));
case 'horizontal'
cfg.width = ft_getopt(cfg, 'width', 0.8 * 1/(nchan+1+2));
cfg.height = ft_getopt(cfg, 'height', 0.8);
end
for i=1:(nchan+2)
switch cfg.layout
case 'vertical'
switch upper(cfg.direction)
case 'TB'
y = 1 - i*(cfg.height/0.8);
case 'BT'
y = 0 + i*(cfg.height/0.8);
otherwise
ft_error('invalid direction "%s" for "%s"', cfg.direction, cfg.layout);
end
x = 0.5*(cfg.width/0.8);
layout.pos (i,:) = [x y];
layout.width (i,1) = cfg.width;
layout.height(i,1) = cfg.height;
case 'horizontal'
switch upper(cfg.direction)
case 'LR'
x = 0 + i*(cfg.width/0.8);
case 'RL'
x = 1 - i*(cfg.width/0.8);
otherwise
ft_error('invalid direction "%s" for "%s"', cfg.direction, cfg.layout);
end
y = 0.5*(cfg.height/0.8);
layout.pos (i,:) = [x y];
layout.width (i,1) = cfg.width;
layout.height(i,1) = cfg.height;
end
if i==(nchan+1)
layout.label{i} = 'SCALE';
elseif i==(nchan+2)
layout.label{i} = 'COMNT';
end
end
elseif isequal(cfg.layout, 'ordered')
assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels');
nchan = length(cfg.channel);
layout.label = cfg.channel;
% the user can specify the number of columns and rows
if isfield(cfg, 'columns') && ~isempty(cfg.columns)
ncol = ft_getopt(cfg, 'columns');
else
ncol = nan; % wil be determined further down
end
if isfield(cfg, 'rows') && ~isempty(cfg.rows)
nrow = ft_getopt(cfg, 'rows');
else
nrow = nan; % wil be determined further down
end
if isnan(ncol) && isnan(nrow)
% the default is a more-or-less square arrangement
ncol = ceil(sqrt(nchan))+1;
nrow = ceil(sqrt(nchan))+1;
elseif isnan(ncol)
ncol = ceil(nchan/nrow);
elseif isnan(nrow)
nrow = ceil(nchan/ncol);
end
switch upper(cfg.direction)
case 'LRTB'
[Y, X] = ndgrid(1:nrow, 1:ncol);
Y = flipud(Y);
X = X';
Y = Y';
case 'RLTB'
[Y, X] = ndgrid(1:nrow, 1:ncol);
X = fliplr(X);
Y = flipud(Y);
X = X';
Y = Y';
case 'LRBT'
[Y, X] = ndgrid(1:nrow, 1:ncol);
X = X';
Y = Y';
case 'RLBT'
[Y, X] = ndgrid(1:nrow, 1:ncol);
X = fliplr(X);
X = X';
Y = Y';
case 'TBLR'
[Y, X] = ndgrid(1:nrow, 1:ncol);
Y = flipud(Y);
case 'TBRL'
[Y, X] = ndgrid(1:nrow, 1:ncol);
X = fliplr(X);
Y = flipud(Y);
case 'BTLR'
[Y, X] = ndgrid(1:nrow, 1:ncol);
case 'BTRL'
[Y, X] = ndgrid(1:nrow, 1:ncol);
X = fliplr(X);
otherwise
ft_error('invalid direction "%s" for "%s"', cfg.direction, cfg.layout);
end
cfg.width = ft_getopt(cfg, 'width', 0.8 * 1/ncol);
cfg.height = ft_getopt(cfg, 'height', 0.8 * 1/nrow);
X = (X-1)*(cfg.width/0.8);
Y = (Y-1)*(cfg.height/0.8);
layout.pos = [X(:) Y(:)];
layout.pos = layout.pos(1:nchan,:);
layout.width = ones(nchan,1) * cfg.width;
layout.height = ones(nchan,1) * cfg.height;
x = max(layout.pos(:,1));
y = min(layout.pos(:,2)) - (cfg.height/0.8);
scalepos = [x y];
x = min(layout.pos(:,1));
y = min(layout.pos(:,2)) - (cfg.height/0.8);
comntpos = [x y];
layout.label{end+1} = 'SCALE';
layout.pos(end+1,:) = scalepos;
layout.width(end+1) = cfg.width;
layout.height(end+1) = cfg.height;
layout.label{end+1} = 'COMNT';
layout.pos(end+1,:) = comntpos;
layout.width(end+1) = cfg.width;
layout.height(end+1) = cfg.height;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to generate layout from other configuration options
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif ischar(cfg.layout)
[p, f, x] = fileparts(cfg.layout);
if isempty(p) && isempty(x)
% this is not a complete filename
% check whether a corresponding lay or mat exists
if exist([cfg.layout '.lay'], 'file')
cfg.layout = [cfg.layout '.lay'];
layout = ft_prepare_layout(cfg);
return
elseif exist([lower(cfg.layout) '.lay'], 'file')
cfg.layout = [cfg.layout '.lay'];
layout = ft_prepare_layout(cfg);
return
elseif exist([cfg.layout '.mat'], 'file')
cfg.layout = [cfg.layout '.mat'];
layout = ft_prepare_layout(cfg);
return
elseif exist([lower(cfg.layout) '.mat'], 'file')
cfg.layout = [cfg.layout '.mat'];
layout = ft_prepare_layout(cfg);
return
end
elseif ft_filetype(cfg.layout, 'matlab')
ft_info('reading layout from file %s\n', cfg.layout);
if ~exist(cfg.layout, 'file')
ft_error('the specified layout file %s was not found', cfg.layout);
end
layout = loadvar(cfg.layout,'layout');
elseif ft_filetype(cfg.layout, 'layout')
if exist(cfg.layout, 'file')
ft_info('reading layout from file %s\n', cfg.layout);
layout = readlay(cfg.layout);
else
[p, f] = fileparts(cfg.layout);
ft_warning('the file "%s" was not found on your path, attempting "%s" instead', cfg.layout, fullfile(p, [f '.mat']));
cfg.layout = fullfile(p, [f '.mat']);
layout = ft_prepare_layout(cfg);
return;
end
elseif ~ft_filetype(cfg.layout, 'layout')
% assume that it points to an electrode file
ft_info('creating layout from sensor description file %s\n', cfg.layout);
sens = ft_read_sens(cfg.layout);
layout = sens2lay(sens, cfg.rotate, cfg.projection, cfg.style, cfg.overlap, cfg.viewpoint, cfg.boxchannel);
end
elseif ~isempty(cfg.grad)
if isstruct(cfg.grad)
ft_info('creating layout from cfg.grad\n');
sens = ft_datatype_sens(cfg.grad);
else
ft_info('creating layout from gradiometer file %s\n', cfg.grad);
sens = ft_read_sens(cfg.grad, 'senstype', 'meg');
end
layout = sens2lay(sens, cfg.rotate, cfg.projection, cfg.style, cfg.overlap, cfg.viewpoint, cfg.boxchannel);
elseif isfield(data, 'grad') && isstruct(data.grad)
ft_info('creating layout from data.grad\n');
sens = ft_datatype_sens(data.grad);
layout = sens2lay(sens, cfg.rotate, cfg.projection, cfg.style, cfg.overlap, cfg.viewpoint, cfg.boxchannel);
elseif ~isempty(cfg.elec)
if isstruct(cfg.elec)
ft_info('creating layout from cfg.elec\n');
sens = ft_datatype_sens(cfg.elec);
else
ft_info('creating layout from electrode file %s\n', cfg.elec);
sens = ft_read_sens(cfg.elec, 'senstype', 'eeg');
end
layout = sens2lay(sens, cfg.rotate, cfg.projection, cfg.style, cfg.overlap, cfg.viewpoint, cfg.boxchannel);
elseif isfield(data, 'elec') && isstruct(data.elec)
ft_info('creating layout from data.elec\n');
sens = ft_datatype_sens(data.elec);
layout = sens2lay(sens, cfg.rotate, cfg.projection, cfg.style, cfg.overlap, cfg.viewpoint, cfg.boxchannel);
elseif ~isempty(cfg.opto)
if isstruct(cfg.opto)
ft_info('creating layout from cfg.opto\n');
sens = ft_datatype_sens(cfg.opto);
else
ft_info('creating layout from optode file %s\n', cfg.opto);
sens = ft_read_sens(cfg.opto, 'senstype', 'nirs');
end
if (hasdata)
layout = opto2lay(sens, data.label, cfg.rotate, cfg.projection, cfg.viewpoint);
else
layout = opto2lay(sens, sens.label, cfg.rotate, cfg.projection, cfg.viewpoint);
end
elseif isfield(data, 'opto') && isstruct(data.opto)
ft_info('creating layout from data.opto\n');
sens = ft_datatype_sens(data.opto);
if (hasdata)
layout = opto2lay(sens, data.label, cfg.rotate, cfg.projection, cfg.viewpoint);
else
layout = opto2lay(sens, sens.label, cfg.rotate, cfg.projection, cfg.viewpoint);
end
elseif (~isempty(cfg.image) || ~isempty(cfg.mesh)) && isempty(cfg.layout)
if ~isempty(cfg.image)
% deal with image file
ft_info('creating layout from image %s\n', cfg.image);
[p, f, e] = fileparts(cfg.image);
switch e
case '.mat'
img = loadvar(cfg.image);
otherwise
img = imread(cfg.image);
end
img = flip(img, 1); % in combination with "axis xy"
figure
if istrue(cfg.bw)
% convert to greyscale image
img = mean(img, 3);
imagesc(img);
colormap gray
else
% plot as RGB image
image(img);
end
elseif ~isempty(cfg.mesh)
if isfield(cfg.mesh, 'sulc')
ft_plot_mesh(cfg.mesh, 'edgecolor', 'none', 'vertexcolor', cfg.mesh.sulc); colormap gray;
else
ft_plot_mesh(cfg.mesh, 'edgecolor', 'none');
end
end
hold on
axis equal
axis off
axis xy
% get the electrode positions
pos = zeros(0,2);
electrodehelp = [ ...
'-----------------------------------------------------\n' ...
'specify electrode locations\n' ...
'press the left mouse button to add another electrode\n' ...
'press backspace on the keyboard to remove the last electrode\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(electrodehelp)
disp(round(pos)); % values are integers/pixels
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
pos = cat(1, pos, [x y]);
% add it to the figure
plot(x, y, 'b.');
plot(x, y, 'yo');
case 8
if size(pos,1)>0
% remove the last point
pos = pos(1:end-1,:);
% completely redraw the figure
cla
if ~isempty(cfg.image)
h = image(img);
else
h = ft_plot_mesh(cfg.mesh, 'edgecolor', 'none', 'vertexcolor', cfg.mesh.sulc);
end
hold on
axis equal
axis off
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
end
case 'q'
again = 0;
otherwise
ft_warning('invalid button (%d)', k);
end
end
% get the interpolation mask
polygon = {};
thispolygon = 1;
polygon{thispolygon} = zeros(0,2);
maskhelp = [ ...
'------------------------------------------------------------------------\n' ...
'specify polygons for masking the topgraphic interpolation\n' ...
'press the left mouse button to add another point to the current polygon\n' ...
'press backspace on the keyboard to remove the last point\n' ...
'press "c" on the keyboard to close this polygon and start with another\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = true;
while again
fprintf(maskhelp);
fprintf('\n');
for i=1:length(polygon)
fprintf('polygon %d has %d points\n', i, size(polygon{i},1));
end
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
if size(polygon{thispolygon},1)>1
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
end
plot(x, y, 'g.-');
case 8 % backspace
if size(polygon{thispolygon},1)>0
% remove the last point
polygon{thispolygon} = polygon{thispolygon}(1:end-1,:);
% completely redraw the figure
cla
if ~isempty(cfg.image)
h = image(img);
else
h = ft_plot_mesh(cfg.mesh, 'edgecolor', 'none', 'vertexcolor', cfg.mesh.sulc);
end
hold on
axis equal
axis off
% plot the electrode positions
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
for i=1:length(polygon)
x = polygon{i}(:,1);
y = polygon{i}(:,2);
if i~=thispolygon
% close the polygon in the figure
x(end) = x(1);
y(end) = y(1);
end
plot(x, y, 'g.-');
end
end
case 'c'
if size(polygon{thispolygon},1)>0
% close the polygon
polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:);
% close the polygon in the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'g.-');
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'q'
if size(polygon{thispolygon},1)>0
% close the polygon
polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:);
% close the polygon in the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'g.-');
end
again = 0;
otherwise
ft_warning('invalid button (%d)', k);
end
end % while again
% remember this set of polygons as the mask
mask = polygon;
% get the outline, e.g. head shape, nose, ears, sulci, etc.
polygon = {};
thispolygon = 1;
polygon{thispolygon} = zeros(0,2);
outlinehelp = [ ...
'-----------------------------------------------------------------------------------\n' ...
'specify polygons for adding outlines (e.g. head shape and sulci) to the layout\n' ...
'press the left mouse button to add another point to the current polygon\n' ...
'press backspace on the keyboard to remove the last point\n' ...
'press "c" on the keyboard to close this polygon and start with another\n' ...
'press "n" on the keyboard to start with another without closing the current polygon\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = true;
while again
fprintf(outlinehelp);
fprintf('\n');
for i=1:length(polygon)
fprintf('polygon %d has %d points\n', i, size(polygon{i},1));
end
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return
end
switch k
case 1
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
if size(polygon{thispolygon},1)>1
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
end
plot(x, y, 'm.-');
case 8 % backspace
if size(polygon{thispolygon},1)>0
% remove the last point
polygon{thispolygon} = polygon{thispolygon}(1:end-1,:);
% completely redraw the figure
cla
if ~isempty(cfg.image)
image(img);
else
ft_plot_mesh(cfg.mesh, 'edgecolor', 'none', 'vertexcolor', cfg.mesh.sulc);
end
hold on
axis equal
axis off
% plot the electrode positions
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
for i=1:length(polygon)
x = polygon{i}(:,1);
y = polygon{i}(:,2);
if i~=thispolygon
% close the polygon in the figure
x(end) = x(1);
y(end) = y(1);
end
plot(x, y, 'm.-');
end
end
case 'c'
if size(polygon{thispolygon},1)>0
x = polygon{thispolygon}(1,1);
y = polygon{thispolygon}(1,2);
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'm.-');
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'n'
if size(polygon{thispolygon},1)>0
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'q'
again = 0;
otherwise
ft_warning('invalid button (%d)', k);
end
end % while again
% remember this set of polygons as the outline
outline = polygon;
% convert the sensor positions into a layout structure
layout.pos = pos;
nchans = size(pos,1);
for i=1:nchans
layout.label{i,1} = num2str(i);
end
% compute the width and height for multiplotting
d = dist(pos');
for i=1:nchans
d(i,i) = inf; % exclude the diagonal
end
mindist = min(d(:));
layout.width = ones(nchans,1) * mindist * 0.8;
layout.height = ones(nchans,1) * mindist * 0.6;
% add the polygons that describe the mask and outline
layout.mask = mask;
layout.outline = outline;
finalhelp = [ ...
'-----------------------------------------------------------------------------------\n' ...
'you should update the channel labels, and check the width and height in the output layout\n' ...
];
fprintf(finalhelp);
fprintf('\n');
else
ft_error('no layout detected, please specify cfg.layout')
end
% make the subset as specified in cfg.channel
cfg.channel = ft_channelselection(cfg.channel, setdiff(layout.label, {'COMNT', 'SCALE'}, 'stable')); % exclude COMNT and SCALE which are not really channels
chansel = match_str(layout.label, vertcat(cfg.channel(:), 'COMNT', 'SCALE')); % include COMNT and SCALE at the end, keep other channels in the order of the layout
% return the layout for the subset of channels
layout.pos = layout.pos(chansel,:);
layout.label = layout.label(chansel);
if strcmpi(cfg.style, '2d')
% width and height only apply to the 2D layout
layout.width = layout.width(chansel);
layout.height = layout.height(chansel);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% overrule the width and height when specified by the user
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(cfg.width)
layout.width(:) = cfg.width;
end
if ~isempty(cfg.height)
layout.height(:) = cfg.height;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check whether the outline and mask are available, create them if needed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (~isfield(layout, 'outline') || ~isfield(layout, 'mask')) && ~strcmpi(cfg.style, '3d')
% the reason to check for style=3d rather than 2d is that cfg.style is also an option in ft_topoplotER and ft_topoplotTFR
% the style option of that function easily "leaks" into here, causing the default 2d not to be selected at the top
if strcmp(cfg.outline, 'circle') || strcmp(cfg.outline, 'doublecirclecross')
% Scale the electrode positions to fit well within a unit circle
ind_scale = find(strcmp('SCALE', layout.label));
ind_comnt = find(strcmp('COMNT', layout.label));
sel = setdiff(1:length(layout.label), [ind_scale ind_comnt]); % these are excluded for scaling
x = layout.pos(sel,1);
y = layout.pos(sel,2);
if strcmp(cfg.center, 'yes')
% the following centers all electrodes around zero
xrange = range(x);
yrange = range(y);
shiftx = min(x);
shifty = min(y);
elseif strcmp(cfg.center, 'no')
% the following prevent topography distortion in case electrodes are not evenly distributed over the whole head
xrange = 2*( max(max(x),abs(min(x)) ));
yrange = 2*( max(max(y),abs(min(y)) ));
shiftx = ( max(max(x),abs(min(x)) )).*sign(min(x));