-
Notifications
You must be signed in to change notification settings - Fork 17
/
pop_roi_connect.m
383 lines (360 loc) · 20 KB
/
pop_roi_connect.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
% pop_roi_connect - call roi_connect to connectivity between ROIs
%
% Usage:
% EEG = pop_roi_connect(EEG, 'key', 'val', ...);
%
% Inputs:
% EEG - EEGLAB dataset containing ROI activity
%
% Optional inputs:
% 'morder' - [integer] Order of autoregressive model. Default is 20.
% 'nepochs' - [integer] number of data epoch. This is useful when
% comparing conditions. if not enough epochs can be extracted
% an error is returned. If there are too many, the first ones
% are selected (selecting the first epochs ensure they are mostly
% contiguous and that the correlation between them is similar
% accross conditions).
% 'naccu' - [integer] Number of accumulation for stats. Default is 0.
% 'methods' - [cell] Cell of strings corresponding to methods.
% 'CS' : Cross spectrum
% 'aCOH' : Coherence
% 'cCOH' : (Complex-valued) Coherency
% 'iCOH' : Absolute value of the imaginary part of Coherency
% 'GC' : Granger Causality
% 'TRGC' : Time-reversed Granger Causality
% 'wPLI' : Weighted Phase Lag Index
% 'PDC' : Partial directed coherence
% 'TRPDC' : Time-reversed partial directed coherence
% 'DTF' : Directed transfer entropy
% 'TRDTF' : Time-reversed directed transfer entropy
% 'MIM' : Multivariate Interaction Measure for each ROI
% 'MIC' : Maximized Imaginary Coherency for each ROI
% 'PAC' : Phase-amplitude coupling between ROIs (see the 'fcomb' and 'bs_outopts' input parameters)
% 'TDE' : Time-delay estimation between two selected ROIs (see the 'tde_regions' and 'tde_freqbands' input parameters)
% 'snippet' - ['on'|off] Option to compute connectivity over snippets. Default is 'off'.
% 'firstsnippet' - ['on'|off] Only use the first snippet (useful for fast computation). Default is 'off'.
% 'snip_length' - ['on'|'off'] Length of the snippets. Default is 60 seconds.
% 'errornosnippet' - ['on'|'off'] Error if snippet too short. Default 'on'.
% 'fcsave_format' - ['mean_snips'|'all_snips'] Option to save mean over snippets
% (shape: 101,68,68) or all snippets (shape: n_snips,101,68,68). Default is 'mean_snips.'
% 'freqresolution' - [integer] Desired frequency resolution (in number of frequencies).
% If specified, the signal is zero padded accordingly. Default is 0 (means no padding).
% 'fcomb' - [struct] Frequency combination for which PAC is computed (in Hz). Must have fields 'low' and
% 'high' with fcomb.low < fcomb.high. For example, fcomb.low = 10 and fcomb.high = 50 if single
% frequencies are used. fcomb.low = [4 8] and fcomb.high = [48 50] if frequency bands are used
% (might take a long time to compute so use with caution). Default is {} (this will cause an error when PAC is selected).
% 'bs_outopts' - [integer] Option which bispectral tensors should be stored in EEG.roi.PAC. Default is 1.
% 1 - store all tensors: b_orig, b_anti, b_orig_norm, b_anti_norm
% 2 - only store: b_orig, b_anti
% 3 - only store: b_orig_norm, b_anti_norm
% 4 - only store: b_orig, b_orig_norm
% 5 - only store: b_anti, b_anti_norm
% 'roi_selection' - [cell array of integers] Cell array of ROI indices {1, 2, 3, ...} indicating for which regions (ROIs) connectivity should be computed.
% Default is empty (in this case, connectivity will be computed for all ROIs).
% 'tde_method' - [integer] TDE method, must be between 1:4, open bispectral_TD_est.m for details. Default is 1.
% 'tde_regions' - [seed target] Array containing the seed and target region for time-delay estimation. Regions need to be passed as region *indices*,
% e.g., [2 10] will compute time-delays from region 2 -> 10 and 10 -> 2, corresponding to the information flow in both directions separately.
% Default is [] (will throw an error).
% 'tde_freqbands' - [f1 f2] Array containing the frequency band for which bispectral time-delays will be estimated. Default is [] (broadband).
% 'conn_stats' - ['on'|'off'] Run statistics on connectivity metrics. Default is 'off'.
% 'nshuf' - [integer] number of shuffles for statistical significance testing. The first shuffle is the true value. Default is 1001.
% 'freqrange' - [min max] frequency range in Hz. This is used to compute and plot p-values. Default is to plot broadband power.
% 'poolsize' - [integer] Number of workers in the parallel pool (check parpool documentation) for parallel computing
%
% Output:
% EEG - EEGLAB dataset with field 'roi' containing connectivity info.
%
% Note: Optional inputs to roi_connectivity_process() are also accepted.
%
% Author: Arnaud Delorme, UCSD, 2019
%
% Example
% p = fileparts(which('eeglab')); % path
% EEG = pop_roi_connect(EEG, 'headmodel', ...
% EEG.dipfit.hdmfile, 'elec2mni', EEG.dipfit.coord_transform, ...
% 'sourcemodel', fullfile(p, 'functions', 'supportfiles', ...
% 'head_modelColin27_5003_Standard-10-5-Cap339.mat'), 'sourcemodel2mni', ...
% [0 -26.6046230000 -46 0.1234625600 0 -1.5707963000 1000 1000 1000]);
%
% Use pop_roi_connectivity(EEG) to conectivity
% Copyright (C) Arnaud Delorme, [email protected]
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.
% TO DO - Arno
% - Centralize reading head mesh and Atlas (there might be a function in
% Fieldtrip to do that) ft_read_volume ft_read_mesh
% - Make compatible with all Fieldtrip and FSL Atlases
% - Downsampling of Atlas - check bug submitted to Fieldtrip
% - Plot inside(blue) vs outside(red) voxels for source volume
function [EEG,com] = pop_roi_connect(EEG, varargin)
com = '';
if nargin < 1
help pop_roi_connect;
return
end
if ~isfield(EEG(1), 'roi') || ~isfield(EEG(1).roi, 'source_roi_data')
error('Cannot find ROI data - ROI data first');
end
if nargin < 2
rowg = [0.1 0.6 1 0.2];
% uigeom = { 1 1 rowg rowg 1 rowg rowg [0.1 0.6 0.9 0.3] 1 rowg 1 [0.5 1 0.35 0.5] [0.5 1 0.35 0.5] [0.5 1 0.35 0.5] [1] [0.9 1.2 1] };
uigeom = { [1] [1.2 1] [1.2 1] [1.2 1] [1.2 1] [1.2 1] [1.2 1] [1.2 1] [1.2 1] [1] [0.2 1 0.35 0.8] [0.2 1 0.35 0.8] [0.2 1 0.35 0.8] [0.2 1 0.35 0.8]};
uilist = { { 'style' 'text' 'string' 'Select connectivity measures' 'fontweight' 'bold' } ...
{ 'style' 'checkbox' 'string' 'Cross-spectrum (CS)' 'tag' 'cs' 'value' 1 } {} ...
{'style' 'checkbox' 'string' '(Complex-valued) Coherency (cCOH)' 'tag' 'ccoh' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Coherence (aCOH)' 'tag' 'acoh' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Imaginary Coherency (iCOH)' 'tag' 'icoh' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Weighted Phase Lag Index (wPLI)' 'tag' 'wpli' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Granger Causality (GC)' 'tag' 'gc' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Time-reversed GC' 'tag' 'trgc' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Partial Directed Coherence (PDC)' 'tag' 'pdc' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Time-reversed PDC' 'tag' 'trpdc' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Directed Transfer Entropy (DTF)' 'tag' 'dtf' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Time-reversed DTF' 'tag' 'trdtf' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Multivariate Interaction Measure (MIM)' 'tag' 'mim' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Maximized Imaginary Coherency (MIC)' 'tag' 'mic' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Phase-Amplitude Coupling (PAC)' 'tag' 'pac' 'value' 0 } ...
{ 'style' 'checkbox' 'string' 'Time Delay Estimation (TDE)' 'tag' 'tde' 'value' 0 } ...
{} ...
{} { 'style' 'text' 'string' 'Autoregressive model order' } { 'style' 'edit' 'string' '20' 'tag' 'morder' } {} ...
{} { 'style' 'text' 'string' 'Bootstrap if any (n)' } { 'style' 'edit' 'string' '' 'tag' 'naccu2' } {} ...
{} { 'style' 'text' 'string' 'Frequency combination in Hz (for PAC) [f1 f2]' } { 'style' 'edit' 'string' '' 'tag' 'fcomb' } {} ...
{} { 'style' 'text' 'string' 'Region selection by index (for TDE) [region1 region2]' } { 'style' 'edit' 'string' '' 'tag' 'tde_regions' } {} };
...
[result,~,~,out] = inputgui('geometry', uigeom, 'uilist', uilist, 'helpcom', 'pophelp(''pop_roi_connect'')', 'title', 'pop_roiconnect - connectivity');
if isempty(result), return, end
% check we have the same naccu
methods = {};
if out.cs, methods = [ methods { 'CS' } ]; end
% if out.coh, methods = [ methods { 'COH' } ]; end
if out.ccoh, methods = [ methods { 'cCOH' } ]; end
if out.acoh, methods = [ methods { 'aCOH' } ]; end
if out.icoh, methods = [ methods { 'iCOH' } ]; end
if out.gc , methods = [ methods { 'GC' } ]; end
if out.trgc, methods = [ methods { 'TRGC' } ]; end
if out.wpli, methods = [ methods { 'wPLI' } ]; end
if out.pdc , methods = [ methods { 'PDC' } ]; end
if out.trpdc, methods = [ methods { 'TRPDC' } ]; end
if out.dtf , methods = [ methods { 'DTF' } ]; end
if out.trdtf, methods = [ methods { 'TRDTF' } ]; end
if out.mim , methods = [ methods { 'MIM' } ]; end
if out.mic, methods = [ methods { 'MIC' } ]; end
if out.pac, methods = [ methods { 'PAC' } ]; end
if out.tde, methods = [ methods { 'TDE' } ]; end
options = { ...
'morder' str2num(out.morder) ...
'naccu' str2num(out.naccu2) ...
'methods' methods ...
'tde_regions' eval( [ '[' out.tde_regions ']' ] )};
if ~isempty(eval( [ '[' out.fcomb ']' ] ))
out_fcomb = eval( [ '[' out.fcomb ']' ] );
fcomb.low = out_fcomb(1);
fcomb.high = out_fcomb(2);
options = [options {'fcomb' fcomb}];
end
else
options = varargin;
end
% decode input parameters
% -----------------------
g = finputcheck(options, ...
{ 'morder' 'integer' { } 20;
'naccu' 'integer' { } 0;
'methods' 'cell' { } { };
'snippet' 'string' { 'on', 'off' } 'off';
'firstsnippet' 'string' { 'on', 'off' } 'off';
'errornosnippet' 'string' { 'on', 'off' } 'off';
'nepochs' 'real' {} [];
'snip_length' 'integer' { } 60;
'fcsave_format' 'string' { 'mean_snips', 'all_snips'} 'mean_snips';
'freqresolution' 'integer' { } 0;
'fcomb' 'struct' { } struct;
'bs_outopts' 'integer' { } 1;
'roi_selection' 'cell' { } { };
'tde_method' 'integer' { 1:4 } 1;
'tde_regions' 'integer' { } [ ];
'tde_freqbands' 'integer' { } [ ];
'conn_stats' 'string' { } 'off'; ...
'nshuf' 'integer' { } 1001; ...
'poolsize' 'integer' { } 1}, 'pop_roi_connect');
if ischar(g), error(g); end
% process multiple datasets
% -------------------------
if length(EEG) > 1
if nargin < 2
[ EEG, com ] = eeg_eval( 'pop_roi_connect', EEG, 'warning', 'off', 'params', options );
else
[ EEG, com ] = eeg_eval( 'pop_roi_connect', EEG, 'params', options );
end
return
end
tmpMethods = setdiff(g.methods, { 'CS' 'COH' 'cCOH' 'aCOH' 'iCOH' 'GC' 'TRGC' 'wPLI' 'PDC' 'TRPDC' 'DTF' 'TRDTF' 'MIM' 'MIC' 'PAC' 'TDE'});
if ~isempty(tmpMethods)
error('Unknown methods %s', vararg2str(tmpMethods))
end
% compute connectivity over snippets
if strcmpi(g.snippet, 'on') && strcmpi(g.conn_stats, 'off')
% n_conn_metrics = length(g.methods);
snippet_length = g.snip_length; % seconds
trials = size(EEG.roi.source_roi_data,3);
pnts = size(EEG.roi.source_roi_data,2);
snip_eps = snippet_length/(pnts/EEG.roi.srate); % snip length/epoch length (how many trials for each snippet)
nsnips = floor(trials/snip_eps);
if nsnips < 1
if strcmpi(g.errornosnippet, 'on')
error('Snippet length cannot exceed data length.\n')
else
fprintf(2, 'Snippet length cannot exceed data length, using the whole data\n')
nsnips = 1;
end
end
diff = (trials * pnts/EEG.roi.srate) - (nsnips * pnts/EEG.roi.srate * snip_eps);
if diff ~= 0
warning(strcat(int2str(diff), ' seconds are thrown away.'));
end
if strcmpi(g.firstsnippet, 'on')
nsnips = 1;
end
% check if Parallel Processing Toolbox is available and licensed
if license('test', 'Distrib_Computing_Toolbox') && ~isempty(ver('parallel'))
if isfield(g, 'poolsize') && isnumeric(g.poolsize) && g.poolsize > 0
% check if there's already an existing parallel pool
currentPool = gcp('nocreate');
if isempty(currentPool)
parpool(g.poolsize);
end
end
else
disp('Parallel Processing Toolbox is not installed or licensed.');
end
tmplist1 = setdiff(g.methods, {'PAC'}); % list of fc metrics without PAC
tmplist2 = intersect(g.methods, {'PAC'});
% store each connectivity metric for each snippet in separate structure
fc_matrices_snips = cell(nsnips, length(tmplist1));
if ~isempty(tmplist2)
switch g.bs_outopts % number of PAC metrics (check documentation)
case 1
bs_matrices_snips = cell(nsnips, 4);
fns = cell(nsnips, 4);
otherwise
bs_matrices_snips = cell(nsnips, 2);
fns = cell(nsnips, 2);
end
end
source_roi_data_save = EEG.roi.source_roi_data;
parfor isnip = 1:nsnips
% for isnip = 1:nsnips
EEG1 = EEG;
begSnip = (isnip-1)* snip_eps + 1;
endSnip = min((isnip-1)* snip_eps + snip_eps, size(source_roi_data_save,3));
roi_snip = source_roi_data_save(:,:, begSnip:endSnip ); % cut source data into snippets
EEG1.roi.source_roi_data = single(roi_snip);
EEG1 = roi_connect(EEG1, 'morder', g.morder, 'naccu', g.naccu, 'methods', g.methods,'freqresolution', g.freqresolution, 'roi_selection', g.roi_selection); % compute connectivity over one snippet
if ~isempty(intersect(g.methods, {'PAC'}))
EEG1 = roi_pac(EEG1, g.fcomb, g.bs_outopts, g.roi_selection);
end
if ~isempty(tmplist1)
tmp_fc_matrices = cell(1, length(tmplist1));
for fc = 1:length(tmplist1)
fc_name = g.methods{fc};
fc_matrix = EEG1.roi.(fc_name);
tmp_fc_matrices{fc} = fc_matrix;
end
fc_matrices_snips(isnip, :) = tmp_fc_matrices;
end
if ~isempty(tmplist2)
tmp_fns = fieldnames(EEG1.roi.PAC);
tmp_bs_matrices = cell(1, length(tmp_fns));
for bs = 1:length(tmp_fns)
bs_matrix = EEG1.roi.PAC.(tmp_fns{bs});
tmp_bs_matrices{bs} = bs_matrix;
end
bs_matrices_snips(isnip, :) = tmp_bs_matrices;
fns(isnip, :) = tmp_fns;
end
end
% shut down current parallel pool only if the toolbox is available
if license('test', 'Distrib_Computing_Toolbox') && ~isempty(ver('parallel'))
poolobj = gcp('nocreate');
if ~isempty(poolobj)
delete(poolobj);
end
end
% compute mean over connectivity of each snippet
if ~isempty(tmplist1)
for fc = 1:length(tmplist1)
fc_name = g.methods{fc};
[first_dim, second_dim, third_dim] = size(fc_matrices_snips{1,fc});
conn_cell = fc_matrices_snips(:, fc); % store all matrices of one metric in a cell
mat = cell2mat(conn_cell);
reshaped = reshape(mat, first_dim, nsnips, second_dim, third_dim);
reshaped = squeeze(permute(reshaped, [2, 1, 3, 4]));
if strcmpi(g.fcsave_format, 'all_snips')
EEG.roi.(fc_name) = reshaped;
else
if nsnips > 1
mean_conn = squeeze(mean(reshaped, 1));
else
mean_conn = reshaped;
end
EEG.roi.(fc_name) = mean_conn; % store mean connectivity in EEG struct
end
end
end
if ~isempty(tmplist2)
fns = fns(1, :);
for bs = 1:length(fns)
[second_dim, third_dim] = size(bs_matrices_snips{1, bs});
conn_cell = bs_matrices_snips(:, bs); % store all matrices of one metric in a cell
mat = cell2mat(conn_cell);
reshaped = reshape(mat, second_dim, nsnips, third_dim);
reshaped = squeeze(permute(reshaped, [2, 1, 3]));
if strcmpi(g.fcsave_format, 'all_snips')
EEG.roi.PAC.(fns{bs}) = reshaped;
else
if nsnips > 1
mean_conn = squeeze(mean(reshaped, 1));
else
mean_conn = reshaped;
end
EEG.roi.PAC.(fns{bs}) = mean_conn; % store mean connectivity in EEG struct
end
end
end
end
if strcmpi(g.snippet, 'off') && strcmpi(g.conn_stats, 'off')
EEG = roi_connect(EEG, 'morder', g.morder, 'naccu', g.naccu, 'methods', g.methods,'freqresolution', g.freqresolution, 'roi_selection', g.roi_selection);
if strcmpi(g.snippet, 'off') && ~isempty(intersect(g.methods, {'PAC'}))
EEG = roi_pac(EEG, g.fcomb, g.bs_outopts, g.roi_selection);
end
if strcmpi(g.snippet, 'off') && ~isempty(intersect(g.methods, {'TDE'}))
EEG = roi_tde(EEG, g.tde_method, g.tde_regions, g.tde_freqbands);
end
end
% TO-DO: add snippet option for stats mode
if strcmpi(g.conn_stats, 'on')
EEG = roi_connstats(EEG, 'methods', g.methods, 'nshuf', g.nshuf, 'roi_selection', g.roi_selection, 'freqresolution', g.freqresolution, 'poolsize', g.poolsize, 'fcomb', g.fcomb);
end
if nargout > 1
com = sprintf( 'EEG = pop_roi_connect(EEG, %s);', vararg2str( options ));
end