-
Notifications
You must be signed in to change notification settings - Fork 0
/
tf_analyses_functions.py
342 lines (285 loc) · 11.8 KB
/
tf_analyses_functions.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
# coding=utf-8
"""
This is a group of function to be used on TF data.
@author: mje
@email: mads [] cnru.dk
"""
from my_settings import *
import numpy as np
import mne
from mne.minimum_norm import (apply_inverse_epochs, read_inverse_operator,
source_induced_power)
from mne.time_frequency import (psd_multitaper, cwt_morlet)
from mne.viz import iter_topography
import matplotlib.pyplot as plt
def calc_ALI(subject, show_plot=False):
"""Function calculates the alpha lateralization index (ALI).
The alpha lateralization index (ALI) is based on:
Huurne, N. ter, Onnink, M., Kan, C., Franke, B., Buitelaar, J.,
& Jensen, O. (2013).
Parameters
----------
subject : string
The name of the subject to calculate ALI for.
show_plot : bool
Whether to plot the data or not.
RETURNS
-------
ali_left : the ALI for the left cue
ali_right : the ALI for the right cue
"""
ctl_left_roi_left_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ctl_left_OCCIPITAL_lh_dSPM"
% (subject))
ctl_right_roi_left_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ctl_left_OCCIPITAL_rh_dSPM"
% (subject))
ctl_left_roi_right_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ctl_right_OCCIPITAL_lh_dSPM"
% (subject))
ctl_right_roi_right_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ctl_right_OCCIPITAL_rh_dSPM"
% (subject))
ALI_left_cue_ctl = ((ctl_left_roi_left_cue.data.mean(axis=0) -
ctl_right_roi_left_cue.data.mean(axis=0)) /
(ctl_left_roi_left_cue.data.mean(axis=0) +
ctl_right_roi_left_cue.data.mean(axis=0)))
ALI_right_cue_ctl = ((ctl_left_roi_right_cue.data.mean(axis=0) -
ctl_right_roi_right_cue.data.mean(axis=0)) /
(ctl_left_roi_right_cue.data.mean(axis=0) +
ctl_right_roi_right_cue.data.mean(axis=0)))
ent_left_roi_left_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ent_left_OCCIPITAL_lh_dSPM"
% (subject))
ent_right_roi_left_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ent_left_OCCIPITAL_rh_dSPM"
% (subject))
ent_left_roi_right_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ent_right_OCCIPITAL_lh_dSPM"
% (subject))
ent_right_roi_right_cue =\
mne.read_source_estimate(tf_folder +
"BP_%s_ent_right_OCCIPITAL_rh_dSPM"
% (subject))
ALI_left_cue_ent = ((ent_left_roi_left_cue.data.mean(axis=0) -
ent_right_roi_left_cue.data.mean(axis=0)) /
(ent_left_roi_left_cue.data.mean(axis=0) +
ent_right_roi_left_cue.data.mean(axis=0)))
ALI_right_cue_ent = ((ent_left_roi_right_cue.data.mean(axis=0) -
ent_right_roi_right_cue.data.mean(axis=0)) /
(ent_left_roi_right_cue.data.mean(axis=0) +
ent_right_roi_right_cue.data.mean(axis=0)))
if show_plot:
times = ent_left_roi_left_cue.times
plt.figure()
plt.plot(times, ALI_left_cue_ctl, 'r', label="ALI Left cue control")
plt.plot(times, ALI_left_cue_ent, 'b', label="ALI Left ent control")
plt.plot(times, ALI_right_cue_ctl, 'g', label="ALI Right cue control")
plt.plot(times, ALI_right_cue_ent, 'm', label="ALI Right ent control")
plt.legend()
plt.title("ALI curves for subject: %s" % subject)
plt.show()
return (ALI_left_cue_ctl, ALI_right_cue_ctl,
ALI_left_cue_ent, ALI_right_cue_ent)
def calc_power(subject, epochs, condition=None, label=None, save=True):
"""Calculate induced power and ITC.
Does TF...
Parameters
----------
subject : string
the subject number.
epochs : ??? # TODO give proper name for epochs file
the epochs to calculate power from.
label : string
restrict to a label.
condition : string
the condition to use if there several in the epochs file.
save : bool
whether for save the results. Defaults to True.
"""
frequencies = np.arange(8, 13, 1) # define frequencies of interest
n_cycles = frequencies / 3.
inverse_operator = read_inverse_operator(mne_folder +
"%s-inv.fif" % subject)
snr = 1.0
lambda2 = 1.0 / snr ** 2
method = "dSPM" # use dSPM method (could also be MNE or sLORETA)
if condition:
epochs_test = epochs[condition]
else:
epochs_test = epochs
power, phase_lock = source_induced_power(epochs_test,
inverse_operator,
frequencies,
label=label,
method=method,
lambda2=lambda2,
n_cycles=n_cycles,
use_fft=True,
pick_ori=None,
baseline=(None, -0.3),
baseline_mode='zscore',
pca=True,
n_jobs=2)
if save:
np.save(tf_folder + "pow_%s_%s-%s_%s_%s_%s.npy" % (subject,
frequencies[0],
frequencies[-1],
label.name,
condition,
method),
power)
np.save(tf_folder + "itc_%s_%s-%s_%s_%s_%s.npy" % (subject,
frequencies[0],
frequencies[-1],
label.name,
condition,
method),
phase_lock)
return power, phase_lock
def calc_psd_epochs(epochs, plot=False):
"""Calculate PSD for epoch.
Parameters
----------
epochs : list of epochs
plot : bool
To show plot of the psds.
It will be average for each condition that is shown.
Returns
-------
psds_vol : numpy array
The psds for the voluntary condition.
psds_invol : numpy array
The psds for the involuntary condition.
"""
tmin, tmax = -0.5, 0.5
fmin, fmax = 2, 90
# n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2
psds_vol, freqs = psd_multitaper(epochs["voluntary"],
tmin=tmin, tmax=tmax,
fmin=fmin, fmax=fmax)
psds_inv, freqs = psd_multitaper(epochs["involuntary"],
tmin=tmin, tmax=tmax,
fmin=fmin, fmax=fmax)
psds_vol = 20 * np.log10(psds_vol) # scale to dB
psds_inv = 20 * np.log10(psds_inv) # scale to dB
if plot:
def my_callback(ax, ch_idx):
"""Executed once you click on one of the channels in the plot."""
ax.plot(freqs, psds_vol_plot[ch_idx], color='red',
label="voluntary")
ax.plot(freqs, psds_inv_plot[ch_idx], color='blue',
label="involuntary")
ax.set_xlabel = 'Frequency (Hz)'
ax.set_ylabel = 'Power (dB)'
ax.legend()
psds_vol_plot = psds_vol.copy().mean(axis=0)
psds_inv_plot = psds_inv.copy().mean(axis=0)
for ax, idx in iter_topography(epochs.info,
fig_facecolor='k',
axis_facecolor='k',
axis_spinecolor='k',
on_pick=my_callback):
ax.plot(psds_vol_plot[idx], color='red', label="voluntary")
ax.plot(psds_inv_plot[idx], color='blue', label="involuntary")
plt.legend()
plt.gcf().suptitle('Power spectral densities')
plt.show()
return psds_vol, psds_inv, freqs
def single_trial_tf(epochs, frequencies, n_cycles):
"""Something here.
Parameters
----------
epochs : Epochs object
The epochs to calculate TF analysis on.
n_cycles : int or numpy array
The number of cycles for the Morlet wavelets.
Returns
-------
results : numpy array
"""
results = []
for j in range(len(epochs)):
tfr = cwt_morlet(epochs.get_data()[j],
sfreq=epochs.info["sfreq"],
freqs=frequencies,
use_fft=True,
n_cycles=n_cycles,
zero_mean=False)
results.append(tfr)
return results
def calc_spatial_resolution(freqs, n_cycles):
"""Calculate the spatial resolution for a Morlet wavelet.
The formula is: (freqs * cycles)*2.
Parameters
----------
freqs : numpy array
The frequencies to be calculated.
n_cycles : int or numpy array
The number of cycles used. Can be integer for the same cycle for all
frequencies, or a numpy array for individual cycles per frequency.
Returns
-------
result : numpy array
The results
"""
result = np.empty_like(freqs)
for i in range(len(result)):
result[i] = (freqs[i] / float(n_cycles[i])) * 2
return result
def calc_wavelet_duration(freqs, n_cycles):
"""Calculate the wavelet duration for a Morlet wavelet in ms.
The formula is: (cycle / frequencies / pi)*1000
Parameters
----------
freqs : numpy array
The frequencies to be calculated.
n_cycles : int or numpy array
The number of cycles used. Can be integer for the same cycle for all
frequencies, or a numpy array for individual cycles per frequency.
Returns
-------
result : numpy array
The results
"""
result = np.empty_like(freqs)
for i in range(len(result)):
result[i] = (float(n_cycles[i]) / freqs[i] / np.pi) * 1000
return result
def single_epoch_tf_source(epochs, inv, src, label):
"""Calculates single trail power
Parameter
---------
epochs : ???
The subject number to use.
inv = inverse_operator
...
src : source space
...
label : label
...
"""
snr = 1.0
lambda2 = 1.0 / snr ** 2
method = "dSPM" # use dSPM method (could also be MNE or sLORETA)
frequencies = np.arange(8, 13, 1)
stcs = apply_inverse_epochs(epochs, inv, lambda2=lambda2, method=method,
label=None, pick_ori=None)
time_series = [stc.extract_label_time_course(labels=label, src=src,
mode="pca_flip")[0]
for stc in stcs]
ts_signed = []
for j in range(len(time_series)):
tmp = time_series[j]
tmp *= np.sign(tmp[np.argmax(np.abs(tmp))])
ts_signed.append(tmp)
tfr = cwt_morlet(np.asarray(ts_signed), epochs.info["sfreq"], frequencies,
use_fft=True, n_cycles=4)
return tfr