summaryrefslogtreecommitdiff
path: root/doc/examples/multi_taper_coh.py
blob: dabf8cf92035020dce28340eb5bc7859cc459ab3 (plain)
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
"""

.. _multi-taper-coh:


================================
Multi-taper coherence estimation
================================


Coherence estimation can be done using windowed-spectra. This is the method
used in the example :ref:`resting-state`. In addition, multi-taper spectral
estimation can be used in order to calculate coherence and also confidence
intervals for the coherence values that result (see :ref:`multi-taper-psd`)


The data analyzed here is an fMRI data-set contributed by Beth Mormino. The
data is taken from a single subject in a"resting-state" scan, in which subjects
are fixating on a cross and maintaining alert wakefulness, but not performing
any other behavioral task.

We start by importing modules/functions we will use in this example and define
variables which will be used as the sampling interval of the TimeSeries
objects and as upper and lower bounds on the frequency range analyzed:

"""

import os

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import csv2rec
import scipy.stats.distributions as dist
from scipy import fftpack

import nitime
from nitime.timeseries import TimeSeries
from nitime import utils
import nitime.algorithms as alg
import nitime.viz
from nitime.viz import drawmatrix_channels
from nitime.analysis import CoherenceAnalyzer, MTCoherenceAnalyzer

TR = 1.89
f_ub = 0.15
f_lb = 0.02

"""

We read in the data into a recarray from a csv file:

"""

data_path = os.path.join(nitime.__path__[0], 'data')

data_rec = csv2rec(os.path.join(data_path, 'fmri_timeseries.csv'))


"""

The first line in the file contains the names of the different brain regions
(or ROI = regions of interest) from which the time-series were derived. We
extract the data into a regular array, while keeping the names to be used later:

"""

roi_names = np.array(data_rec.dtype.names)
nseq = len(roi_names)
n_samples = data_rec.shape[0]
data = np.zeros((nseq, n_samples))

for n_idx, roi in enumerate(roi_names):
    data[n_idx] = data_rec[roi]


"""

We normalize the data in each of the ROIs to be in units of % change:

"""

pdata = utils.percent_change(data)

"""

We start by performing the detailed analysis, but note that a significant
short-cut is presented below, so if you just want to know how to do this
(without needing to understand the details), skip on down.

We start by defining how many tapers will be used and calculate the values of
the tapers and the associated eigenvalues of each taper:

"""

NW = 4
K = 2 * NW - 1

tapers, eigs = alg.dpss_windows(n_samples, NW, K)

"""

We multiply the data by the tapers and derive the fourier transform and the
magnitude of the squared spectra (the power) for each tapered time-series:

"""


tdata = tapers[None, :, :] * pdata[:, None, :]
tspectra = fftpack.fft(tdata)
## mag_sqr_spectra = np.abs(tspectra)
## np.power(mag_sqr_spectra, 2, mag_sqr_spectra)


"""

Coherence for real sequences is symmetric, so we calculate this for only half
the spectrum (the other half is equal):

"""

L = n_samples / 2 + 1
sides = 'onesided'

"""

We estimate adaptive weighting of the tapers, based on the data (see
:ref:`multi-taper-psd` for an explanation and references):

"""

w = np.empty((nseq, K, L))
for i in xrange(nseq):
    w[i], _ = utils.adaptive_weights(tspectra[i], eigs, sides=sides)


"""

We proceed to calculate the coherence. We initialize empty data containers:

"""

csd_mat = np.zeros((nseq, nseq, L), 'D')
psd_mat = np.zeros((2, nseq, nseq, L), 'd')
coh_mat = np.zeros((nseq, nseq, L), 'd')
coh_var = np.zeros_like(coh_mat)


"""

Looping over the ROIs:

"""

for i in xrange(nseq):
    for j in xrange(i):

        """

        We calculate the multi-tapered cross spectrum between each two
        time-series:

        """

        sxy = alg.mtm_cross_spectrum(
           tspectra[i], tspectra[j], (w[i], w[j]), sides='onesided'
         )

        """

        And the individual PSD for each:

        """

        sxx = alg.mtm_cross_spectrum(
           tspectra[i], tspectra[i], w[i], sides='onesided'
           )
        syy = alg.mtm_cross_spectrum(
           tspectra[j], tspectra[j], w[j], sides='onesided'
           )

        psd_mat[0, i, j] = sxx
        psd_mat[1, i, j] = syy

        """

        Coherence is : $Coh_{xy}(\lambda) = \frac{|{f_{xy}(\lambda)}|^2}{f_{xx}(\lambda) \cdot f_{yy}(\lambda)}$

        """

        coh_mat[i, j] = np.abs(sxy) ** 2
        coh_mat[i, j] /= (sxx * syy)
        csd_mat[i, j] = sxy

        """

        The variance from the different samples is calculated using a jack-knife
        approach:

        """

        if i != j:
            coh_var[i, j] = utils.jackknifed_coh_variance(
               tspectra[i], tspectra[j], eigs, adaptive=True,
               )


"""

This measure is normalized, based on the number of tapers:

"""

coh_mat_xform = utils.normalize_coherence(coh_mat, 2 * K - 2)


"""

We calculate 95% confidence intervals based on the jack-knife variance
calculation:

"""

t025_limit = coh_mat_xform + dist.t.ppf(.025, K - 1) * np.sqrt(coh_var)
t975_limit = coh_mat_xform + dist.t.ppf(.975, K - 1) * np.sqrt(coh_var)


utils.normal_coherence_to_unit(t025_limit, 2 * K - 2, t025_limit)
utils.normal_coherence_to_unit(t975_limit, 2 * K - 2, t975_limit)

if L < n_samples:
    freqs = np.linspace(0, 1 / (2 * TR), L)
else:
    freqs = np.linspace(0, 1 / TR, L, endpoint=False)


"""

We look only at frequencies between 0.02 and 0.15 (the physiologically
relevant band, see http://imaging.mrc-cbu.cam.ac.uk/imaging/DesignEfficiency:

"""

freq_idx = np.where((freqs > f_lb) * (freqs < f_ub))[0]

"""

We extract the coherence and average over all these frequency bands:

"""

coh = np.mean(coh_mat[:, :, freq_idx], -1)  # Averaging on the last dimension


"""

The next line calls the visualization routine which displays the data

"""


fig01 = drawmatrix_channels(coh,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0,
                            title='MTM Coherence')


"""

.. image:: fig/multi_taper_coh_01.png

Next we perform the same analysis, using the nitime object oriented interface.

We start by initializing a TimeSeries object with this data and with the
sampling_interval provided above. We set the metadata 'roi' field with the ROI
names.


"""

T = TimeSeries(pdata, sampling_interval=TR)
T.metadata['roi'] = roi_names


"""

We initialize an MTCoherenceAnalyzer object with the TimeSeries object

"""

C2 = MTCoherenceAnalyzer(T)

"""

The relevant indices in the Analyzer object are derived:

"""

freq_idx = np.where((C2.frequencies > 0.02) * (C2.frequencies < 0.15))[0]


"""
The call to C2.coherence triggers the computation and this is averaged over the
frequency range of interest in the same line and then displayed:

"""

coh = np.mean(C2.coherence[:, :, freq_idx], -1)  # Averaging on the last dimension
fig02 = drawmatrix_channels(coh,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0,
                            title='MTCoherenceAnalyzer')


"""

.. image:: fig/multi_taper_coh_02.png


For comparison, we also perform the analysis using the standard
CoherenceAnalyzer object, which does the analysis using Welch's windowed
periodogram, instead of the multi-taper spectral estimation method (see
:ref:`resting_state` for a more thorough analysis of this data using this
method):

"""

C3 = CoherenceAnalyzer(T)

freq_idx = np.where((C3.frequencies > f_lb) * (C3.frequencies < f_ub))[0]

#Extract the coherence and average across these frequency bands:
coh = np.mean(C3.coherence[:, :, freq_idx], -1)  # Averaging on the last dimension
fig03 = drawmatrix_channels(coh,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0,
                            title='CoherenceAnalyzer')


"""

.. image:: fig/multi_taper_coh_03.png


plt.show() is called in order to display the figures:


"""

plt.show()