-
Notifications
You must be signed in to change notification settings - Fork 31
/
tvfcgs.py
executable file
·380 lines (270 loc) · 11.5 KB
/
tvfcgs.py
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
# -*- coding: utf-8 -*-
""" Time-Varying Functional Connectivity Graphs
Time-varying functional connectivity graphs (TVFCGs) (Dimitriadis2010_, Falani2008_) introduce the
idea of processing overlapping segments of neuroelectric signals by defining a
frequency-dependent time window in which the synchronization is estimated;
and then tabulating the results as adjacency matrices. These matrices have a
natural graph-based representation called “functional connectivity graphs”
(FCGs).
An important aspect of the TVFCGs is the “cycle-criterion” (CC) (Cohen2008_).
It regulates the amount of the oscillation cycles that will be considered in
measuring the phase synchrony. In the original proposal :math:`CC = 2.0` was
introduced, resulting into a time-window with width twice the lower period.
TVFCGs on the other, consider the given lower frequency that correspond to the
possibly synchronized oscillations of each brain rhythm and the sampling
frequency. This newly defined frequency-depedent time-window is sliding over
the time series and the network connectivity is estimated. The overlapping
is determined by an arbitrary step parameter.
Given a multi-channel recording data matrix :math:`X^{m \\times n}` of
size :math:`m \\times n` (with :math:`m` channels, and :math:`n` samples), a
frequency range with :math:`F_{up}` and :math:`F_{lo}` the upper and lower
limits, :math:`fs` the sampling frequency, :math:`step` and :math:`CC`, the
computation of these graphs proceeds as follows:
Firstly, based on the :math:`CC` and the specified frequency range
(:math:`F_{lo}` and :math:`fs` ) the window size calculated:
.. math::
w_{len} = \\frac{ CC }{ F_{lo} } fs
Then, this window is moving per :math:`step` samples and the average
synchronization is computed (between the channels, in a pairwise manner)
resulting into :math:`\\frac{n}{step}` adjacency matrices of size
:math:`n \\times n`.
|
-----
.. [Cohen2008] Cohen, M. X. (2008). Assessing transient cross-frequency coupling in EEG data. Journal of neuroscience methods, 168(2), 494-499.
.. [Dimitriadis2010] Dimitriadis, S. I., Laskaris, N. A., Tsirka, V., Vourkas, M., Micheloyannis, S., & Fotopoulos, S. (2010). Tracking brain dynamics via time-dependent network analysis. Journal of neuroscience methods, 193(1), 145-155.
.. [Falani2008] Fallani, F. D. V., Latora, V., Astolfi, L., Cincotti, F., Mattia, D., Marciani, M. G., ... & Babiloni, F. (2008). Persistent patterns of interconnection in time-varying cortical networks estimated from high-resolution EEG recordings in humans during a simple motor act. Journal of Physics A: Mathematical and Theoretical, 41(22), 224014.
"""
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>
import numpy as np
from .fc.estimator import Estimator
def tvfcg(data, estimator_instance, fb, fs, cc=2.0, step=5.0, pairs=None):
""" Time-Varying Functional Connectivity Graphs
The TVFCGs are computed from the input ``data`` by employing the given
synchronization estimator (``estimator_instance``).
Parameters
----------
data : array-like, shape(n_channels, n_samples)
Multichannel recording data.
estimator_instance : object
An object of type :mod:`dyconnmap.fc.Estimator`.
fb : list of length 2
The lower and upper frequency.
fs : float
Sampling frequency.
cc : float
Cycle criterion.
step : int
The amount of samples the window will move/slide over the time series.
pairs : array-like or `None`
- If an `array-like` is given, notice that each element is a tuple of length two.
- If `None` is passed, complete connectivity will be assumed.
Returns
-------
fcgs : array-like, shape(n_windows, n_channels, n_channels)
The computed FCGs.
"""
preprocess, estimator, avg_func = _validate_estimator(estimator_instance)
# Preprocess the data (estimator function)
pp_data = preprocess(data)
#
n_channels, n_samples = np.shape(data)
# window_length = np.int32(np.round((cc / fb[0]) * fs))
# windows = np.int32(np.round((n_samples - window_length) / step))
windows, window_length = tvfcg_compute_windows(data, fb, fs, cc, step)
if window_length >= n_samples:
raise Exception(
"The size of window cannot be greater than the number of samples"
)
fcgs = np.zeros(
(windows, n_channels, n_channels), dtype=estimator_instance.data_type
)
if pairs is None:
pairs = [
(win_id, int(win_id * step), int(window_length + (win_id * step)), c1, c2)
for win_id in range(windows)
for c1 in range(0, n_channels)
for c2 in range(c1, n_channels)
if c1 != c2
]
for pair in pairs:
win_id, start, end, c1, c2 = pair
slice1 = pp_data[c1, ..., start:end]
slice2 = pp_data[c2, ..., start:end]
# slice = None
# try:
slice_ts, _ = estimator(slice1, slice2)
# except:
# slice = estimator(slice1, slice2)
fcgs[win_id, c1, c2] = avg_func(slice_ts)
return fcgs
def tvfcg_cfc(
data, estimator_instance, fb_lo, fb_hi, fs=128, cc=2.0, step=5, pairs=None
):
""" Time-Varying Functional Connectivity Graphs (for Cross frequency Coupling)
The TVFCGs are computed from the input ``data`` by employing the given
cross frequency coupling synchronization estimator (``estimator_instance``).
Parameters
----------
data : array-like, shape(n_channels, n_samples)
Multichannel recording data.
estimator_instance : object
An object of type :mod:`dyconnmap.fc.Estimator`.
fb_lo : list of length 2
The low and high frequencies.
fb_hi : list of length 2
The low and high frequencies.
fs : float
Sampling frequency.
cc : float
Cycle criterion.
step : int
The amount of samples the window will move/slide over the time series.
pairs : array-like or `None`
- If an `array-like` is given, notice that each element is a tuple of length two.
- If `None` is passed, complete connectivity will be assumed.
Returns
-------
fcgs : array-like, shape(n_windows, n_channels, n_channels)
The computed Cross-Frequency FCGs.
Notes
-----
Not all available estimators in the :mod:`dyconnmap.fc` are valid for estimating
cross frequency coupling.
"""
preprocess, estimator, avg_func = _validate_estimator(estimator_instance)
# Preprocess the data (estimator function)
pp_data1, pp_data2 = preprocess(data)
#
n_channels, n_samples = np.shape(data)
# window_length = np.int32(np.round((cc / fb_lo[0]) * fs))
# windows = np.int32(np.round((n_samples - window_length) / step))
windows, window_length = tvfcg_compute_windows(data, fb_lo, fs, cc, step)
if window_length >= n_samples:
raise Exception(
"The size of window cannot be greater than the number of samples"
)
fcgs = np.zeros((windows, n_channels, n_channels))
if pairs is None:
pairs = [
(win_id, (win_id * step), window_length + (win_id * step), c1, c2)
for win_id in range(windows)
for c1 in range(0, n_channels)
for c2 in range(c1, n_channels)
if c1 != c2
]
for pair in pairs:
win_id, start, end, c1, c2 = pair
slice1 = pp_data1[c1, ..., start:end]
slice2 = pp_data2[c2, ..., start:end]
slice_ts, _ = estimator(slice1, slice2)
aslice = avg_func(slice_ts)
fcgs[win_id, c1, c2] = aslice
return fcgs
def tvfcg_ts(ts, fb, fs=128, cc=2.0, step=5, pairs=None, avg_func=np.mean):
""" Time-Varying Function Connectivity Graphs (from time series)
This implementation operates directly on the given estimated synchronization
time series (``ts``) and the mean value inside the window is computed.
Parameters
----------
ts : array-like, shape(n_channels, n_samples)
Multichannel synchronization time series.
fb : list of length 2
The lower and upper frequency.
fs : float
Sampling frequency.
cc : float
Cycle criterion.
step : int
The amount of samples the window will move/slide over the time series.
pairs : array-like or `None`
- If an `array-like` is given, notice that each element is a tuple of length two.
- If `None` is passed, complete connectivity will be assumed.
Returns
-------
fcgs : array-like
The computed FCGs.
"""
n_channels, n_channels, n_samples = np.shape(ts)
window_length = np.int32(np.round((cc / fb[0]) * fs))
windows = np.int32(np.round((n_samples - window_length) / step))
if window_length >= n_samples:
raise Exception(
"The size of window cannot be greater than the number of samples"
)
fcgs = np.zeros((windows, n_channels, n_channels))
if pairs is None:
pairs = [
(win_id, (win_id * step), window_length + (win_id * step), c1, c2)
for win_id in range(windows)
for c1 in range(n_channels)
for c2 in range(c1, n_channels)
]
for pair in pairs:
win_id, start, end, c1, c2 = pair
slice_ts = ts[c1, c2, start:end]
fcgs[win_id, c1, c2] = avg_func(slice_ts)
return fcgs
def tvfcg_compute_windows(data, fb_lo, fs, cc, step):
""" Compute TVFCGs Sliding Windows
A helper function that computes the size and number of sliding windows
given the parameters.
Parameters
----------
data : array-like, shape(n_channels, n_samples)
Multichannel recording data.
fb_lo :
fb : list of length 2
The lower and upper frequency.
fs : float
Sampling frequency.
cc : float
Cycle criterion.
step : int
Stepping.
Returns
-------
windows : int
The total number of sliding windows.
window_length : int
The length of a sliding window; number of samples used to estimated the connectivity.
"""
*_, n_samples = np.shape(data)
window_length = np.int32(np.round((cc / fb_lo[0]) * fs))
windows = np.int32(np.round((n_samples - window_length) / step))
# print("window_length = {0}".format(window_length))
if window_length >= n_samples:
raise Exception(
"The size of window cannot be greater than the number of samples"
)
return windows, window_length
def _validate_estimator(estimator_instance):
"""
Perform common validity checks for a given estimator.
Parameters
----------
estimator_instance : object
An instance of `dyconnmap.fc.Estimator`
Returns
-------
preprocess : function
A callable function for preprocessing the data.
estimator : function
A callable function for estimating the synchronization.
avg : function
A callable function for computing the average on each slice.
Notes
-----
This function is used mainly internally.
"""
if not isinstance(estimator_instance, Estimator):
raise Exception("Given object is not an Estimator.")
preprocess = getattr(estimator_instance, "preprocess")
estimator = getattr(estimator_instance, "estimate_pair")
avg = getattr(estimator_instance, "mean")
if not callable(preprocess):
raise Exception("Preprocess method is not callable.")
if not callable(estimator):
raise Exception("Estimator method is not callabled.")
if not callable(avg):
raise Exception("Mean method is not callable.")
return preprocess, estimator, avg