/
ft_sourceanalysis.m
1310 lines (1170 loc) · 62.1 KB
/
ft_sourceanalysis.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 [source] = ft_sourceanalysis(cfg, data, baseline)
% FT_SOURCEANALYSIS performs beamformer dipole analysis on EEG or MEG data
% after preprocessing and a timelocked or frequency analysis
%
% Use as
% [source] = ft_sourceanalysis(cfg, freq)
% or
% [source] = ft_sourceanalysis(cfg, timelock)
%
% where the second input argument with the data should be organised in a structure
% as obtained from the FT_FREQANALYSIS or FT_TIMELOCKANALYSIS function. The
% configuration "cfg" is a structure containing information about source positions
% and other options.
%
% The different source reconstruction algorithms that are implemented are
% cfg.method = 'lcmv' linear constrained minimum variance beamformer
% 'sam' synthetic aperture magnetometry
% 'dics' dynamic imaging of coherent sources
% 'pcc' partial canonical correlation/coherence
% 'mne' minimum norm estimation
% 'rv' scan residual variance with single dipole
% 'music' multiple signal classification
% 'sloreta' standardized low-resolution electromagnetic tomography
% 'eloreta' exact low-resolution electromagnetic tomography
% The DICS and PCC methods are for frequency or time-frequency domain data, all other
% methods are for time domain data. ELORETA can be used both for time, frequency and
% time-frequency domain data.
%
% The complete grid with dipole positions and optionally precomputed leadfields is
% constructed using FT_PREPARE_SOURCEMODEL. It can be specified as as a regular 3-D
% grid that is aligned with the axes of the head coordinate system using
% cfg.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto')
% cfg.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto')
% cfg.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto')
% cfg.resolution = number (e.g. 1 cm) for automatic grid generation
% If the source model destribes a triangulated cortical sheet, it is described as
% cfg.sourcemodel.pos = N*3 matrix with the vertex positions of the cortical sheet
% cfg.sourcemodel.tri = M*3 matrix that describes the triangles connecting the vertices
% Alternatively the position of a few dipoles at locations of interest can be
% user-specified, for example obtained from an anatomical or functional MRI
% cfg.sourcemodel.pos = N*3 matrix with position of each source
% cfg.sourcemodel.inside = N*1 vector with boolean value whether grid point is inside brain (optional)
% cfg.sourcemodel.dim = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional)
%
% Besides the source positions, you may also include previously computed
% spatial filters and/or leadfields using
% cfg.sourcemodel.filter
% cfg.sourcemodel.leadfield
%
% The following strategies are supported to obtain statistics for the source parameters using
% multiple trials in the data, either directly or through a resampling-based approach
% cfg.rawtrial = 'no' or 'yes' construct filter from single trials, apply to single trials. Note that you also may want to set cfg.keeptrials='yes' to keep all trial information, especially if using in combination with sourcemodel.filter
% cfg.jackknife = 'no' or 'yes' jackknife resampling of trials
% cfg.pseudovalue = 'no' or 'yes' pseudovalue resampling of trials
% cfg.bootstrap = 'no' or 'yes' bootstrap resampling of trials
% cfg.numbootstrap = number of bootstrap replications (e.g. number of original trials)
% If none of these options is specified, the average over the trials will
% be computed prior to computing the source reconstruction.
%
% To obtain statistics over the source parameters between two conditions, you
% can also use a resampling procedure that reshuffles the trials over both
% conditions. In that case, you should call the function with two datasets
% containing single trial data like
% [source] = ft_sourceanalysis(cfg, freqA, freqB)
% [source] = ft_sourceanalysis(cfg, timelockA, timelockB)
% and you should specify
% cfg.randomization = 'no' or 'yes'
% cfg.permutation = 'no' or 'yes'
% cfg.numrandomization = number, e.g. 500
% cfg.numpermutation = number, e.g. 500 or 'all'
%
% If you have not specified a sourcemodel with pre-computed leadfields, the leadfield
% for each source position will be computed on the fly, in the lower level function that
% is called for the heavy lifting. In that case you can modify parameters for the forward
% computation, e.g. by reducing the rank (i.e. remove the weakest orientation), or by
% normalizing each column.
% cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG)
% cfg.backproject = 'yes' or 'no', determines when reducerank is applied whether the
% lower rank leadfield is projected back onto the original linear
% subspace, or not (default = 'yes')
% cfg.normalize = 'yes' or 'no' (default = 'no')
% cfg.normalizeparam = depth normalization parameter (default = 0.5)
% cfg.weight = number or Nx1 vector, weight for each dipole position to compensate
% for the size of the corresponding patch (default = 1)
%
% Other configuration options are
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.frequency = single number (in Hz)
% cfg.latency = single number in seconds, for time-frequency analysis
% cfg.refchan = reference channel label (for coherence)
% cfg.refdip = reference dipole location (for coherence)
% cfg.supchan = suppressed channel label(s)
% cfg.supdip = suppressed dipole location(s)
% cfg.keeptrials = 'no' or 'yes'
% cfg.keepleadfield = 'no' or 'yes'
%
% Some options need to be specified as method specific options, and determine the low-level computation of the inverse operator.
% The functionality (and applicability) of the (sub-)options are documented in the lower-level ft_inverse_<method> functions.
% Replace <method> with one of the supported methods.
% cfg.<method>.lambda = number or empty for automatic default
% cfg.<method>.kappa = number or empty for automatic default
% cfg.<method>.tol = number or empty for automatic default
% cfg.<method>.projectnoise = 'no' or 'yes'
% cfg.<method>.keepfilter = 'no' or 'yes'
% cfg.<method>.keepcsd = 'no' or 'yes'
% cfg.<method>.keepmom = 'no' or 'yes'
% cfg.<method>.feedback = 'no', 'text', 'textbar', 'gui' (default = 'text')
%
% The volume conduction model of the head should be specified as
% cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL
%
% The EEG or MEG sensor positions can be present in the data or can be specified as
% cfg.elec = structure with electrode positions or filename, see FT_READ_SENS
% cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS
%
% To facilitate data-handling and distributed computing you can use
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_SOURCEDESCRIPTIVES, FT_SOURCESTATISTICS, FT_PREPARE_LEADFIELD,
% FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL
% Undocumented local options:
% cfg.numcomponents
% cfg.refchannel
% cfg.trialweight = 'equal' or 'proportional'
% cfg.<method>.powmethod = 'lambda1' or 'trace'
% Copyright (c) 2003-2008, F.C. Donders Centre, 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 debug
ft_preamble loadvar data baseline
ft_preamble provenance data baseline
% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
return
end
% the baseline data can be passed as input argument or can be read from disk
hasbaseline = exist('baseline', 'var');
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', {'comp', 'timelock', 'freq'}, 'feedback', 'yes');
if hasbaseline
baseline = ft_checkdata(baseline, 'datatype', {'comp', 'timelock', 'freq'}, 'feedback', 'yes');
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, 'forbidden', {'parallel', 'trials'});
cfg = ft_checkconfig(cfg, 'forbidden', {'foi', 'toi'});
cfg = ft_checkconfig(cfg, 'renamed', {'toilim', 'latency'});
cfg = ft_checkconfig(cfg, 'renamed', {'foilim', 'frequency'});
cfg = ft_checkconfig(cfg, 'renamed', {'jacknife', 'jackknife'});
cfg = ft_checkconfig(cfg, 'renamed', {'refchannel', 'refchan'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'power', 'dics'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'coh_refchan', 'dics'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'coh_refdip', 'dics'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'dics_cohrefchan', 'dics'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'dics_cohrefdip', 'dics'});
cfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'grid', 'sourcemodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'elecfile', 'elec'});
cfg = ft_checkconfig(cfg, 'renamed', {'gradfile', 'grad'});
cfg = ft_checkconfig(cfg, 'renamed', {'optofile', 'opto'});
% determine the type of input data
istimelock = ft_datatype(data, 'timelock');
isfreq = ft_datatype(data, 'freq');
iscomp = ft_datatype(data, 'comp');
if ~any([isfreq iscomp istimelock])
ft_error('input data is not recognized');
end
% set the defaults
if istimelock
cfg.method = ft_getopt(cfg, 'method', 'lcmv');
elseif isfreq
cfg.method = ft_getopt(cfg, 'method', 'dics');
end
% ensure that the method is specified
ft_checkopt(cfg, 'method', 'char');
if isequal(cfg.method, 'harmony')
ft_error('The harmony implementation does not work at present. Please contact the main developer of this method directly');
end
% put the low-level options pertaining to the source reconstruction method in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', cfg.method);
% move some fields from cfg.method back to the top-level configuration
cfg = ft_checkconfig(cfg, 'createtopcfg', cfg.method);
% put the low-level options pertaining to the dipole grid in their own field
cfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg
cfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg
% put the low-level options pertaining to the sourcemodel in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});
% move some fields from cfg.sourcemodel back to the top-level configuration
cfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});
% get the low-level options for the inverse estimation method, these are method specific
cfg.(cfg.method) = ft_getopt(cfg, cfg.method);
cfg.(cfg.method).keepfilter = ft_getopt(cfg.(cfg.method), 'keepfilter', 'no');
cfg.(cfg.method).keepcsd = ft_getopt(cfg.(cfg.method), 'keepcsd', 'no');
cfg.(cfg.method).keepmom = ft_getopt(cfg.(cfg.method), 'keepmom', 'yes');
cfg.(cfg.method).projectnoise = ft_getopt(cfg.(cfg.method), 'projectnoise', 'no');
cfg.(cfg.method).feedback = ft_getopt(cfg.(cfg.method), 'feedback', 'text');
cfg.(cfg.method).lambda = ft_getopt(cfg.(cfg.method), 'lambda', []);
cfg.(cfg.method).kappa = ft_getopt(cfg.(cfg.method), 'kappa', []);
cfg.(cfg.method).tol = ft_getopt(cfg.(cfg.method), 'tol', []);
cfg.(cfg.method).invmethod = ft_getopt(cfg.(cfg.method), 'invmethod', []);
cfg.(cfg.method).powmethod = ft_getopt(cfg.(cfg.method), 'powmethod', []);
% get any further options
cfg.keepleadfield = ft_getopt(cfg, 'keepleadfield', 'no');
cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no');
cfg.trialweight = ft_getopt(cfg, 'trialweight', 'equal');
cfg.jackknife = ft_getopt(cfg, 'jackknife', 'no');
cfg.pseudovalue = ft_getopt(cfg, 'pseudovalue', 'no');
cfg.bootstrap = ft_getopt(cfg, 'bootstrap', 'no');
cfg.singletrial = ft_getopt(cfg, 'singletrial', 'no');
cfg.rawtrial = ft_getopt(cfg, 'rawtrial', 'no');
cfg.randomization = ft_getopt(cfg, 'randomization', 'no');
cfg.numrandomization = ft_getopt(cfg, 'numrandomization', 100);
cfg.permutation = ft_getopt(cfg, 'permutation', 'no');
cfg.numpermutation = ft_getopt(cfg, 'numpermutation', 100);
cfg.wakewulf = ft_getopt(cfg, 'wakewulf', 'yes');
cfg.killwulf = ft_getopt(cfg, 'killwulf', 'yes');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.latency = ft_getopt(cfg, 'latency', 'all');
cfg.frequency = ft_getopt(cfg, 'frequency', 'all');
% these only apply to DICS and PCC
cfg.refdip = ft_getopt(cfg, 'refdip', []);
cfg.supdip = ft_getopt(cfg, 'supdip', []);
cfg.refchan = ft_getopt(cfg, 'refchan', []);
cfg.supchan = ft_getopt(cfg, 'supchan', []);
if hasbaseline && (strcmp(cfg.randomization, 'no') && strcmp(cfg.permutation, 'no'))
ft_error('input of two conditions only makes sense if you want to randomize or permute');
elseif ~hasbaseline && (strcmp(cfg.randomization, 'yes') || strcmp(cfg.permutation, 'yes'))
ft_error('randomization or permutation requires that you give two conditions as input');
end
if sum([strcmp(cfg.jackknife, 'yes'), strcmp(cfg.bootstrap, 'yes'), strcmp(cfg.pseudovalue, 'yes'), strcmp(cfg.singletrial, 'yes'), strcmp(cfg.rawtrial, 'yes'), strcmp(cfg.randomization, 'yes'), strcmp(cfg.permutation, 'yes')])>1
ft_error('jackknife, bootstrap, pseudovalue, singletrial, rawtrial, randomization and permutation are mutually exclusive');
end
if strcmp(cfg.rawtrial, 'yes') && isfield(cfg, 'sourcemodel') && ~isfield(cfg.sourcemodel, 'filter')
ft_warning('Using each trial to compute its own filter is not currently recommended. Use this option only with precomputed filters in cfg.sourcemodel.filter');
end
if ~isempty(cfg.refchan)
cfg.refchan = ft_channelselection(cfg.refchan, data.label);
assert(numel(cfg.refchan)>0, 'cfg.refchan is not present in the data');
end
if ~isempty(cfg.supchan)
cfg.supchan = ft_channelselection(cfg.supchan, data.label);
assert(numel(cfg.supchan)>0, 'cfg.supchan is not present in the data');
end
% spectrally decomposed data can have label and/or labelcmb
if ~isfield(data, 'label') && isfield(data, 'labelcmb')
% the code further down assumes that data.label is present
% we can construct it from all channel combinations
data.label = unique(data.labelcmb(:));
end
% make the selection of channels consistent with the data
cfg.channel = ft_channelselection(cfg.channel, data.label);
% keep the refchan and supchan
cfg.channel = ft_channelselection([cfg.channel(:); cfg.refchan(:)], data.label);
cfg.channel = ft_channelselection([cfg.channel(:); cfg.supchan(:)], data.label);
% start with an empty output structure
source = [];
if istimelock
tmpcfg = keepfields(cfg, {'channel', 'latency', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
% keep the time axis in the output
tmpcfg.avgovertime = 'no';
data = ft_selectdata(tmpcfg, data);
% restore the provenance information
[cfg, data] = rollback_provenance(cfg, data);
% copy the descriptive fields to the output
source = copyfields(data, source, {'time'});
elseif isfreq
tmpcfg = keepfields(cfg, {'channel', 'latency', 'frequency', 'nanmean', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
if ismember(cfg.method, {'pcc' 'dics'})
tmpcfg.avgoverfreq = 'yes';
if isfield(data, 'time')
tmpcfg.avgovertime = 'yes';
end
end
% include the refchan and supchan if specified
tmpcfg.channel = ft_channelselection([cfg.channel(:); cfg.refchan(:); cfg.supchan(:)], data.label);
data = ft_selectdata(tmpcfg, data);
% restore the provenance information
[cfg, data] = rollback_provenance(cfg, data);
% copy the descriptive fields to the output
source = copyfields(data, source, {'time', 'freq', 'cumtapcnt'});
if ismember(cfg.method, {'pcc' 'dics'})
cfg.frequency = data.freq; % should be a single number here
if isfield(data, 'time')
cfg.latency = data.time; % should be a single number here
end
end
end
if isfreq && isfield(data, 'labelcmb')
% ensure that the cross-spectral densities are chan_chan_therest,
% otherwise the latency and frequency selection could fail, so we don't
% need to worry about linearly indexed cross-spectral densities below
% this point, this step may take some time, if multiple trials are
% present in the data
fprintf('converting the linearly indexed channelcombinations into a square CSD-matrix\n');
data = ft_checkdata(data, 'cmbstyle', 'full');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% prepare the sourcemodel, headmodel, sensors and/or leadfields
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(cfg.refdip) || ~isempty(cfg.supdip)
ft_notice('computing the leadfields on the fly');
% the leadfields for refdip and supdip have to be computed on the fly; to ensure
% that the leadfields for the grid are consistent, these will also be computed on
% the fly
if isfield(cfg.sourcemodel, 'leadfield')
ft_warning('ignoring the precomputed leadfield that are provided');
cfg.sourcemodel = rmfield(cfg.sourcemodel, 'leadfield');
end
if isfield(cfg.sourcemodel, 'filter')
ft_warning('ignoring the precomputed filters that are provided');
cfg.sourcemodel = rmfield(cfg.sourcemodel, 'filter');
end
% collect and preprocess the electrodes/gradiometer and head model
[headmodel, sens, cfg] = prepare_headmodel(cfg, data);
% construct the dipole positions on which the source reconstruction will be done
tmpcfg = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid', 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'reducerank', 'backproject', 'normalize', 'normalizeparam', 'weight', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
tmpcfg.headmodel = headmodel;
if ft_senstype(sens, 'eeg')
tmpcfg.elec = sens;
elseif ft_senstype(sens, 'meg')
tmpcfg.grad = sens;
end
sourcemodel = ft_prepare_sourcemodel(tmpcfg);
elseif isfield(cfg.sourcemodel, 'filter')
ft_notice('using precomputed filters, not computing any leadfields');
sourcemodel = keepfields(cfg.sourcemodel, {'pos', 'tri', 'dim', 'unit', 'coordsys', 'inside', 'filter', 'filterdimord', 'label', 'cfg'});
if ~isfield(sourcemodel, 'label')
ft_warning('the labels are missing for the precomputed filters, assuming that they were computed with the same channel selection');
sourcemodel.label = cfg.channel;
end
% select the channels corresponding to the data and the user configuration
tmpcfg = keepfields(cfg, 'channel');
sourcemodel = ft_selectdata(tmpcfg, sourcemodel);
% sort the channels to be consistent with the data
[dum, chansel] = match_str(data.label, sourcemodel.label);
sourcemodel.label = sourcemodel.label(chansel);
for i=1:numel(sourcemodel.filter)
if ~isempty(sourcemodel.filter{i})
sourcemodel.filter{i} = sourcemodel.filter{i}(:, chansel);
end
end
% ensure that the channels are consistent with the data
if isempty(ft_getopt(cfg, 'refchan')) && isempty(ft_getopt(cfg, 'supchan'))
assert(isequal(sourcemodel.label(:), cfg.channel(:)), 'cannot match the channels in the sourcemodel to those in the data');
else
% the data and cfg also includes the recfchan or supchan
assert(all(ismember(sourcemodel.label, cfg.channel)), 'cannot match the channels in the sourcemodel to those in the data');
end
% no forward computations are needed
headmodel = [];
sens = [];
cfg = removefields(cfg, {'headmodel', 'elec', 'grad'});
elseif isfield(cfg.sourcemodel, 'leadfield')
ft_notice('using precomputed leadfields');
sourcemodel = keepfields(cfg.sourcemodel, {'pos', 'tri', 'dim', 'unit', 'coordsys', 'inside', 'leadfield', 'leadfielddimord', 'label', 'cfg', 'subspace'});
if ~isfield(sourcemodel, 'label')
ft_warning('the labels are missing for the precomputed leadfields, assuming that they were computed with the same channel selection');
sourcemodel.label = cfg.channel;
end
% select the channels corresponding to the data and the user configuration
tmpcfg = keepfields(cfg, 'channel');
sourcemodel = ft_selectdata(tmpcfg, sourcemodel);
% sort the channels to be consistent with the data
[dum, chansel] = match_str(data.label, sourcemodel.label);
sourcemodel.label = sourcemodel.label(chansel);
for i=1:numel(sourcemodel.leadfield)
if ~isempty(sourcemodel.leadfield{i})
sourcemodel.leadfield{i} = sourcemodel.leadfield{i}(chansel, :);
end
end
% ensure that the channels are consistent with the data
if isempty(ft_getopt(cfg, 'refchan')) && isempty(ft_getopt(cfg, 'supchan'))
assert(isequal(sourcemodel.label(:), cfg.channel(:)), 'cannot match the channels in the sourcemodel to those in the data');
else
% the data and cfg also includes the recfchan or supchan
assert(all(ismember(sourcemodel.label, cfg.channel)), 'cannot match the channels in the sourcemodel to those in the data');
end
% no forward computations are needed
headmodel = [];
sens = [];
cfg = removefields(cfg, {'headmodel', 'elec', 'grad'});
elseif istrue(cfg.keepleadfield) || istrue(cfg.permutation) || istrue(cfg.randomization) || istrue(cfg.bootstrap) || istrue(cfg.jackknife) || istrue(cfg.pseudovalue) || istrue(cfg.singletrial) || istrue(cfg.rawtrial)
ft_notice('computing the leadfields in advance');
% collect and preprocess the electrodes/gradiometer and head model
[headmodel, sens, cfg] = prepare_headmodel(cfg, data);
% construct the dipole positions on which the source reconstruction will be done
tmpcfg = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid', 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'reducerank', 'backproject', 'normalize', 'normalizeparam', 'weight', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
tmpcfg.headmodel = headmodel;
if ft_senstype(sens, 'eeg')
tmpcfg.elec = sens;
elseif ft_senstype(sens, 'meg')
tmpcfg.grad = sens;
end
sourcemodel = ft_prepare_leadfield(tmpcfg);
% no further forward computations are needed, but keep them in the cfg
needheadmodel = false;
headmodel = [];
sens = [];
else
ft_notice('computing the leadfields on the fly');
% collect and preprocess the electrodes/gradiometer and head model
[headmodel, sens, cfg] = prepare_headmodel(cfg, data);
% construct the dipole positions on which the source reconstruction will be done
tmpcfg = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid', 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'reducerank', 'backproject', 'normalize', 'normalizeparam', 'weight', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
tmpcfg.headmodel = headmodel;
if ft_senstype(sens, 'eeg')
tmpcfg.elec = sens;
elseif ft_senstype(sens, 'meg')
tmpcfg.grad = sens;
end
sourcemodel = ft_prepare_sourcemodel(tmpcfg);
end % if refdip/supdip, precomputed filter, leadfield, keepfilter, keepleadfield, or so
% It might be that the number of channels in the data, the number of
% channels in the electrode/gradiometer definition and the number of
% channels in the localspheres volume conduction model are different.
% Hence a subset of the data channels will be used.
Nchans = length(cfg.channel);
if ~iscomp && contains(data.dimord, 'freq')
Nfreq = numel(data.freq);
else
Nfreq = 1;
end
if ~iscomp && contains(data.dimord, 'time')
Ntime = numel(data.time);
else
Ntime = 1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% do frequency domain source reconstruction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfreq && any(strcmp(cfg.method, {'dics', 'pcc', 'eloreta', 'mne','harmony', 'rv', 'music'}))
switch cfg.method
case 'pcc'
if hasbaseline
ft_error('not supported')
end
tmpcfg = keepfields(cfg, {'keeptrials', 'rawtrial', 'refchan', 'channel'});
tmpcfg.refchan = []; % for PCC prepare_freq_matrices should not know explicitly about the refchan
% select the data in the channels and the frequency of interest
[Cf, Cr, Pr, Ntrials, tmpcfg] = prepare_freq_matrices(tmpcfg, data);
if ~isempty(cfg.refchan)
[dum, refchanindx] = match_str(cfg.refchan, tmpcfg.channel);
else
refchanindx = [];
end
if ~isempty(cfg.supchan)
[dum, supchanindx] = match_str(cfg.supchan, tmpcfg.channel);
else
supchanindx = [];
end
Nchans = length(tmpcfg.channel); % update the number of channels
% if the input data has a complete Fourier spectrum, it can be projected through the filters
if isfield(data, 'fourierspctrm')
[dum, datchanindx] = match_str(tmpcfg.channel, data.label);
fbin = nearest(data.freq, cfg.frequency);
if strcmp(data.dimord, 'chan_freq')
avg = data.fourierspctrm(datchanindx, fbin);
elseif strcmp(data.dimord, 'rpt_chan_freq') || strcmp(data.dimord, 'rpttap_chan_freq')
avg = transpose(data.fourierspctrm(:, datchanindx, fbin));
elseif strcmp(data.dimord, 'chan_freq_time')
tbin = nearest(data.time, cfg.latency);
avg = data.fourierspctrm(datchanindx, fbin, tbin);
elseif strcmp(data.dimord, 'rpt_chan_freq_time') || strcmp(data.dimord, 'rpttap_chan_freq_time')
tbin = nearest(data.time, cfg.latency);
avg = transpose(data.fourierspctrm(:, datchanindx, fbin, tbin));
end
else
avg = [];
end
case {'eloreta' 'mne' 'rv' 'music' 'harmony'}
% these can handle both a csd matrix and a fourier matrix
tmpcfg = keepfields(cfg, {'keeptrials', 'rawtrial', 'refchan', 'channel'});
[Cf, Cr, Pr, Ntrials, tmpcfg] = prepare_freq_matrices(tmpcfg, data);
% if the input data has a complete fourier spectrum, it can be projected through the filters
if isfield(data, 'fourierspctrm')
[dum, datchanindx] = match_str(tmpcfg.channel, data.label);
fbin = nearest(data.freq, cfg.frequency);
if numel(fbin)==1, fbin = fbin.*[1 1]; end
if strcmp(data.dimord, 'chan_freq')
avg = data.fourierspctrm(datchanindx, fbin);
elseif strcmp(data.dimord, 'rpt_chan_freq') || strcmp(data.dimord, 'rpttap_chan_freq')
avg = permute(data.fourierspctrm(:, datchanindx, fbin(1):fbin(2)), [2 1 3]);
elseif strcmp(data.dimord, 'chan_freq_time')
tbin = nearest(data.time, cfg.latency);
if numel(tbin)==1, tbin = tbin.*[1 1]; end
avg = data.fourierspctrm(datchanindx, fbin(1):fbin(2), tbin(1):tbin(2));
elseif strcmp(data.dimord, 'rpt_chan_freq_time') || strcmp(data.dimord, 'rpttap_chan_freq_time')
tbin = nearest(data.time, cfg.latency);
if numel(tbin)==1, tbin = tbin.*[1 1]; end
avg = permute(data.fourierspctrm(:, datchanindx, fbin(1):fbin(2), tbin(1):tbin(2)), [2 1 3 4]);
end
else % The input data is a CSD matrix, this is enough for computing source power, coherence and residual power.
ft_warning('no fourierspctra in the input data, so the frequency domain dipole moments cannot be computed');
avg = [];
end
case 'dics'
tmpcfg = keepfields(cfg, {'keeptrials', 'rawtrial', 'refchan', 'channel'});
tmpcfg.channel = setdiff(cfg.channel, cfg.refchan, 'stable'); % remove the refchan, ensure that the ordering does not change, see https://github.com/fieldtrip/fieldtrip/issues/1587
% select the data in the channels and the frequency of interest
[Cf, Cr, Pr, Ntrials, tmpcfg] = prepare_freq_matrices(tmpcfg, data);
Nchans = length(tmpcfg.channel); % update the number of channels
% assign a descriptive name to each of the dics sub-methods, the default is power only
if ~isempty(cfg.refdip)
submethod = 'dics_refdip';
elseif ~isempty(cfg.refchan)
submethod = 'dics_refchan';
else
submethod = 'dics_power';
end
otherwise
ft_error('unsupported cfg.method');
end
% fill these with NaNs, so that I dont have to treat them separately
if isempty(Cr), Cr = nan(Ntrials, Nchans, Nfreq, Ntime); end
if isempty(Pr), Pr = nan(Ntrials, Nfreq, Ntime); end
if hasbaseline
% repeat the conversion for the baseline condition
[bCf, bCr, bPr, Nbaseline, tmpcfg] = prepare_freq_matrices(tmpcfg, baseline);
% fill these with NaNs, so that I dont have to treat them separately
if isempty(bCr), bCr = nan(Nbaseline, Nchans, 1); end
if isempty(bPr), bPr = nan(Nbaseline, 1, 1); end
% rename the active condition for convenience
aCf = Cf;
aCr = Cr;
aPr = Pr;
% this is required for averaging 2 conditions using prepare_resampled_data
cfg2 = [];
cfg2.numcondition = 2;
% this is required for randomizing/permuting 2 conditions using prepare_resampled_data
cfg.numcondition = 2;
end
% prepare the resampling of the trials, or average the data if multiple trials are present and no resampling is necessary
if (Ntrials<=1) && (strcmp(cfg.jackknife, 'yes') || strcmp(cfg.bootstrap, 'yes') || strcmp(cfg.pseudovalue, 'yes') || strcmp(cfg.singletrial, 'yes') || strcmp(cfg.rawtrial, 'yes') || strcmp(cfg.randomization, 'yes') || strcmp(cfg.permutation, 'yes'))
ft_error('multiple trials required in the data\n');
elseif strcmp(cfg.permutation, 'yes')
% compute the cross-spectral density matrix without resampling
[dum, avg_aCf, avg_aCr, avg_aPr, avg_bCf, avg_bCr, avg_bPr] = prepare_resampled_data(cfg2 , aCf, aCr, aPr, bCf, bCr, bPr);
% compute the cross-spectral density matrix with random permutation
[dum, rnd_aCf, rnd_aCr, rnd_aPr, rnd_bCf, rnd_bCr, rnd_bPr] = prepare_resampled_data(cfg, aCf, aCr, aPr, bCf, bCr, bPr);
% concatenate the different resamplings
Cf = cat(1, reshape(avg_aCf, [1 Nchans Nchans]), reshape(avg_bCf, [1 Nchans Nchans]), rnd_aCf, rnd_bCf);
Cr = cat(1, reshape(avg_aCr, [1 Nchans 1 ]), reshape(avg_bCr, [1 Nchans 1 ]), rnd_aCr, rnd_bCr);
Pr = cat(1, reshape(avg_aPr, [1 1 1 ]), reshape(avg_bPr, [1 1 1 ]), rnd_aPr, rnd_bPr);
% clear temporary working copies
clear avg_aCf avg_aCr avg_aPr avg_bCf avg_bCr avg_bPr
clear rnd_aCf rnd_aCr rnd_aPr rnd_bCf rnd_bCr rnd_bPr
% the order of the resamplings should be [avgA avgB rndA rndB rndA rndB rndA rndB ....]
Nrepetitions = 2*cfg.numpermutation + 2;
order = [1 2 3:2:Nrepetitions 4:2:Nrepetitions];
Cf = Cf(order,:,:);
Cr = Cr(order,:,:);
Pr = Pr(order,:,:);
elseif strcmp(cfg.randomization, 'yes')
% compute the cross-spectral density matrix without resampling
[dum, avg_aCf, avg_aCr, avg_aPr, avg_bCf, avg_bCr, avg_bPr] = prepare_resampled_data(cfg2 , aCf, aCr, aPr, bCf, bCr, bPr);
% compute the cross-spectral density matrix with random resampling
[dum, rnd_aCf, rnd_aCr, rnd_aPr, rnd_bCf, rnd_bCr, rnd_bPr] = prepare_resampled_data(cfg, aCf, aCr, aPr, bCf, bCr, bPr);
% concatenate the different resamplings
Cf = cat(1, reshape(avg_aCf, [1 Nchans Nchans]), reshape(avg_bCf, [1 Nchans Nchans]), rnd_aCf, rnd_bCf);
Cr = cat(1, reshape(avg_aCr, [1 Nchans 1 ]), reshape(avg_bCr, [1 Nchans 1 ]), rnd_aCr, rnd_bCr);
Pr = cat(1, reshape(avg_aPr, [1 1 1 ]), reshape(avg_bPr, [1 1 1 ]), rnd_aPr, rnd_bPr);
% clear temporary working copies
clear avg_aCf avg_aCr avg_aPr avg_bCf avg_bCr avg_bPr
clear rnd_aCf rnd_aCr rnd_aPr rnd_bCf rnd_bCr rnd_bPr
% the order of the resamplings should be [avgA avgB rndA rndB rndA rndB rndA rndB ....]
Nrepetitions = 2*cfg.numrandomization + 2;
order = [1 2 3:2:Nrepetitions 4:2:Nrepetitions];
Cf = Cf(order,:,:);
Cr = Cr(order,:,:);
Pr = Pr(order,:,:);
elseif strcmp(cfg.jackknife, 'yes')
% compute the cross-spectral density matrix with jackknife resampling
[cfg, Cf, Cr, Pr] = prepare_resampled_data(cfg, Cf, Cr, Pr);
Nrepetitions = Ntrials;
elseif strcmp(cfg.bootstrap, 'yes')
% compute the cross-spectral density matrix with bootstrap resampling
[cfg, Cf, Cr, Pr] = prepare_resampled_data(cfg, Cf, Cr, Pr);
Nrepetitions = cfg.numbootstrap;
elseif strcmp(cfg.pseudovalue, 'yes')
% compute the cross-spectral density matrix with pseudovalue resampling
[cfg, Cf, Cr, Pr] = prepare_resampled_data(cfg, Cf, Cr, Pr);
Nrepetitions = Ntrials+1;
elseif strcmp(cfg.singletrial, 'yes')
% The idea is that beamformer uses the average covariance to construct the
% filter and applies it to the single trial covariance/csd. The problem
% is that beamformer will use the averaged covariance/csd to estimate the
% power and not the single trial covariance/csd
ft_error('this option contains a bug, and is therefore not supported at the moment');
Cf = Cf; % FIXME, should be averaged and repeated for each trial
Cr = Cr; % FIXME, should be averaged and repeated for each trial
Pr = Pr; % FIXME, should be averaged and repeated for each trial
Nrepetitions = Ntrials;
elseif strcmp(cfg.rawtrial, 'yes')
% keep all the individual trials, do not average them
Cf = Cf;
Cr = Cr;
Pr = Pr;
Nrepetitions = Ntrials;
elseif Ntrials>1
% compute the average from the individual trials
Cf = reshape(sum(Cf, 1) / Ntrials, [Nchans Nchans]);
Cr = reshape(sum(Cr, 1) / Ntrials, [Nchans 1]);
Pr = reshape(sum(Pr, 1) / Ntrials, [1 1]);
Nrepetitions = 1;
elseif Ntrials==1
% no rearrangement of trials is neccesary, the data already represents the average
Cf = Cf;
Cr = Cr;
Pr = Pr;
Nrepetitions = 1;
end
% reshape so that it also looks like one trial (out of many)
if Nrepetitions==1
Cf = reshape(Cf , [1 Nchans Nchans Nfreq Ntime]);
Cr = reshape(Cr , [1 Nchans Nfreq Ntime]);
Pr = reshape(Pr , [1 Nfreq Ntime]);
end
% get the relevant low level options from the cfg and convert into key-value pairs
tmpcfg = cfg.(cfg.method);
% disable console feedback for the low-level function in case of multiple repetitions
if Nrepetitions > 1
tmpcfg.feedback = 'none';
end
methodopt = ft_cfg2keyval(tmpcfg);
% construct the low-level options for the leadfield computation as key-value pairs, these are passed to the inverse function and FT_COMPUTE_LEADFIELD
leadfieldopt = {};
leadfieldopt = ft_setopt(leadfieldopt, 'reducerank', ft_getopt(cfg, 'reducerank'));
leadfieldopt = ft_setopt(leadfieldopt, 'backproject', ft_getopt(cfg, 'backproject'));
leadfieldopt = ft_setopt(leadfieldopt, 'normalize', ft_getopt(cfg, 'normalize'));
leadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(cfg, 'normalizeparam'));
leadfieldopt = ft_setopt(leadfieldopt, 'weight', ft_getopt(cfg, 'weight'));
if Nrepetitions > 1
ft_progress('init', cfg.(cfg.method).feedback, 'scanning repetition...');
end
for i=1:Nrepetitions
size_Cf = size(Cf);
squeeze_Cf = reshape(Cf(i,:,:), size_Cf(2:end));
if Nrepetitions > 1
ft_progress(i/Nrepetitions, 'scanning repetition %d from %d', i, Nrepetitions);
end
switch cfg.method
case 'dics'
if strcmp(submethod, 'dics_power')
dip(i) = ft_inverse_dics(sourcemodel, sens, headmodel, [], squeeze_Cf, methodopt{:}, leadfieldopt{:});
elseif strcmp(submethod, 'dics_refchan')
dip(i) = ft_inverse_dics(sourcemodel, sens, headmodel, [], squeeze_Cf, methodopt{:}, leadfieldopt{:}, 'Cr', Cr(i,:), 'Pr', Pr(i));
elseif strcmp(submethod, 'dics_refdip')
dip(i) = ft_inverse_dics(sourcemodel, sens, headmodel, [], squeeze_Cf, methodopt{:}, leadfieldopt{:}, 'refdip', cfg.refdip);
end
case 'pcc'
if ~isempty(avg) && istrue(cfg.rawtrial)
% FIXME added by jansch because an appropriate subselection of avg
% should be done first (i.e. select the tapers that belong to this
% repetition
ft_error('rawtrial in combination with pcc has been temporarily disabled');
else
dip(i) = ft_inverse_pcc(sourcemodel, sens, headmodel, avg, squeeze_Cf, methodopt{:}, leadfieldopt{:}, 'refdip', cfg.refdip, 'refchan', refchanindx, 'supdip', cfg.supdip, 'supchan', supchanindx);
end
case 'eloreta'
dip(i) = ft_inverse_eloreta(sourcemodel, sens, headmodel, avg, squeeze_Cf, methodopt{:}, leadfieldopt{:});
case 'mne'
dip(i) = ft_inverse_mne(sourcemodel, sens, headmodel, avg, methodopt{:}, leadfieldopt{:});
case 'harmony'
dip(i) = ft_inverse_harmony(sourcemodel, sens, headmodel, avg, methodopt{:}, leadfieldopt{:});
% ft_error(sprintf('method ''%s'' is unsupported for source reconstruction in the frequency domain', cfg.method));
case {'rv'}
dip(i) = ft_inverse_rv(sourcemodel, sens, headmodel, avg, methodopt{:}, leadfieldopt{:});
case {'music'}
ft_error('method ''%s'' is currently unsupported for source reconstruction in the frequency domain', cfg.method);
otherwise
ft_error('unsupported cfg.method');
end
end
if Nrepetitions > 1
ft_progress('close');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% do time domain source reconstruction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif istimelock && any(strcmp(cfg.method, {'lcmv', 'sam', 'mne', 'harmony', 'rv', 'music', 'pcc', 'mvl', 'sloreta', 'eloreta'}))
% determine the size of the data
Nsamples = length(data.time);
Nchans = length(data.label);
if isfield(data, 'cov') && length(size(data.cov))==3
Ntrials = size(data.cov,1);
elseif isfield(data, 'trial') && length(size(data.trial))==3
Ntrials = size(data.trial,1);
else
Ntrials = 1;
end
if isfield(data, 'cov')
% use the estimated data covariance matrix
hascovariance = true;
else
% add a identity covariance matrix, this simplifies the handling of the different source reconstruction methods
% since the covariance is only used by some reconstruction methods and might not always be present in the data
if Ntrials==1
data.cov = eye(Nchans);
else
data.cov = zeros(Ntrials,Nchans,Nchans);
for i=1:Ntrials
data.cov(i,:,:) = eye(Nchans);
end
end
hascovariance = false;
ft_warning('No covariance matrix found, assuming identity covariance matrix');
end
if strcmp(cfg.method, 'pcc')
if hasbaseline
ft_error('not supported')
end
tmpcfg = [];
tmpcfg.channel = cfg.channel;
if ~isempty(cfg.refchan)
tmpcfg.channel = [tmpcfg.channel(:); cfg.refchan(:)];
end
if ~isempty(cfg.supchan)
tmpcfg.channel = [tmpcfg.channel cfg.supchan(:)'];
end
% select the data in the channels of interest
[dum, datchanindx] = match_str(tmpcfg.channel, data.label);
if Ntrials==1
data.avg = data.avg(datchanindx,:);
data.cov = data.cov(datchanindx,datchanindx);
else
data.cov = data.cov(:,datchanindx,datchanindx);
data.trial = data.trial(:,datchanindx,:);
end
data.label = data.label(datchanindx);
if ~isempty(cfg.refchan)
[dum, refchanindx] = match_str(cfg.refchan, data.label);
else
refchanindx = [];
end
if ~isempty(cfg.supchan)
[dum, supchanindx] = match_str(cfg.supchan, data.label);
else
supchanindx = [];
end
Nchans = length(tmpcfg.channel); % update the number of channels
else
% HACK: use the default code
% select the channels of interest
[dum, datchanindx] = match_str(cfg.channel, data.label);
if strcmp(data.dimord, 'chan_time')
% It is in principle possible to have timelockanalysis with
% keeptrial=yes and only a single trial in the raw data.
% In that case the covariance should be represented as Nchan*Nchan
data.avg = data.avg(datchanindx,:);
%data.cov = reshape(data.cov, length(datchanindx), length(datchanindx));
data.cov = data.cov(datchanindx,datchanindx);
elseif strcmp(data.dimord, 'rpt_chan_time')
data.cov = data.cov(:,datchanindx,datchanindx);
data.trial = data.trial(:,datchanindx,:);
else
ft_error('unexpected dimord');
end
data.label = data.label(datchanindx);
Nchans = length(data.label);
end
if hasbaseline
% baseline and active are only available together for resampling purposes,
% or as a noise covariance for SAM beamforming
% hence I assume here that there are multiple trials in both
if isfield(baseline, 'avg')
baseline.avg = baseline.avg(datchanindx,:);
baseline.cov = baseline.cov(datchanindx,datchanindx);
else
baseline.cov = baseline.cov(:,datchanindx,datchanindx);
baseline.trial = baseline.trial(:,datchanindx,:);
end
% this is required for averaging 2 conditions using prepare_resampled_data
cfg2 = [];
cfg2.numcondition = 2;
end
% prepare the resampling of the trials, or average the data if multiple trials are present and no resampling is necessary
if (strcmp(cfg.jackknife, 'yes') || strcmp(cfg.bootstrap, 'yes') || strcmp(cfg.pseudovalue, 'yes') || strcmp(cfg.singletrial, 'yes') || strcmp(cfg.rawtrial, 'yes') || strcmp(cfg.randomization, 'yes')) && ~strcmp(data.dimord, 'rpt_chan_time')
ft_error('multiple trials required in the data\n');
elseif strcmp(cfg.permutation, 'yes')
% compute the average and covariance without resampling
[dum, avgA, covA, avgB, covB] = prepare_resampled_data(cfg2 , data.trial, data.cov, baseline.trial, baseline.cov);
% compute the average and covariance with random permutation
[cfg, avRA, coRA, avRB, coRB] = prepare_resampled_data(cfg, data.trial, data.cov, baseline.trial, baseline.cov);
% concatenate the different resamplings
avg = cat(1, reshape(avgA, [1 Nchans Nsamples]), reshape(avgB, [1 Nchans Nsamples]), avRA, avRB);
Cy = cat(1, reshape(covA, [1 Nchans Nchans ]), reshape(covB, [1 Nchans Nchans ]), coRA, coRB);
% clear temporary working copies
clear avgA avgB covA covB
clear avRA avRB coRA coRB
% the order of the resamplings should be [avgA avgB randA randB randA randB randA randB ....]
Nrepetitions = 2*cfg.numpermutation + 2;
order = [1 2 3:2:Nrepetitions 4:2:Nrepetitions];
avg = avg(order,:,:);
Cy = Cy (order,:,:);
elseif strcmp(cfg.randomization, 'yes')
% compute the average and covariance without resampling
[dum, avgA, covA, avgB, covB] = prepare_resampled_data(cfg2 , data.trial, data.cov, baseline.trial, baseline.cov);
% compute the average and covariance with random resampling
[cfg, avRA, coRA, avRB, coRB] = prepare_resampled_data(cfg, data.trial, data.cov, baseline.trial, baseline.cov);
% concatenate the different resamplings
avg = cat(1, reshape(avgA, [1 Nchans Nsamples]), reshape(avgB, [1 Nchans Nsamples]), avRA, avRB);
Cy = cat(1, reshape(covA, [1 Nchans Nchans ]), reshape(covB, [1 Nchans Nchans ]), coRA, coRB);
% clear temporary working copies
clear avgA avgB covA covB
clear avRA avRB coRA coRB
% the order of the resamplings should be [avgA avgB randA randB randA randB randA randB ....]
Nrepetitions = 2*cfg.numrandomization + 2;
order = [1 2 3:2:Nrepetitions 4:2:Nrepetitions];
avg = avg(order,:,:);
Cy = Cy (order,:,:);
elseif strcmp(cfg.jackknife, 'yes')
% compute the jackknife repetitions for the average and covariance
[cfg, avg, Cy] = prepare_resampled_data(cfg, data.trial, data.cov);
Nrepetitions = Ntrials;
elseif strcmp(cfg.bootstrap, 'yes')
% compute the bootstrap repetitions for the average and covariance
[cfg, avg, Cy] = prepare_resampled_data(cfg, data.trial, data.cov);
Nrepetitions = cfg.numbootstrap;
elseif strcmp(cfg.pseudovalue, 'yes')
% compute the pseudovalue repetitions for the average and covariance
[cfg, avg, Cy] = prepare_resampled_data(cfg, data.trial, data.cov);
Nrepetitions = Ntrials+1;
elseif strcmp(cfg.singletrial, 'yes')
% The idea is that beamformer uses the average covariance to construct the
% filter and applies it to the single trial covariance/csd. The problem
% is that beamformer will use the averaged covariance/csd to estimate the
% power and not the single trial covariance/csd
ft_error('this option contains a bug, and is therefore not supported at the moment');
% average the single-trial covariance matrices
Cy = mean(data.cov,1);
% copy the average covariance matrix for every individual trial
Cy = repmat(Cy, [Ntrials 1 1]);
% keep the single-trial ERFs, rename them to avg for convenience
avg = data.trial;
Nrepetitions = Ntrials;
elseif strcmp(cfg.rawtrial, 'yes')
% do not do any resampling, keep the single-trial covariances
Cy = data.cov;
% do not do any resampling, keep the single-trial ERFs (rename them to avg for convenience)
avg = data.trial;
Nrepetitions = Ntrials;
elseif Ntrials>1
% average the single-trial covariance matrices
Cy = reshape(mean(data.cov,1), [Nchans Nchans]);
% compute the average ERF
avg = shiftdim(mean(data.trial,1),1);
Nrepetitions = 1;
elseif Ntrials==1
% select the average covariance matrix
Cy = data.cov;
% select the average ERF
avg = data.avg;
Nrepetitions = 1;
end