/
cohere.py
1276 lines (932 loc) · 36.9 KB
/
cohere.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
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
"""
Coherency is an analogue of correlation, calculated in the frequency
domain. This is a useful quantity for describing a system of oscillators
coupled with delay. This is because the coherency captures not only the
magnitude of the time-shift-independent correlation between the time-series
(termed 'coherence'), but can also be used in order to estimate the size of the
time-delay (the phase-delay between the time-series in a particular frequency
band).
"""
import numpy as np
from nitime.lazy import scipy_fftpack as fftpack
from nitime.lazy import matplotlib_mlab as mlab
from .spectral import get_spectra, get_spectra_bi
import nitime.utils as utils
# To suppport older versions of numpy that don't have tril_indices:
from nitime.index_utils import tril_indices
def coherency(time_series, csd_method=None):
r"""
Compute the coherency between the spectra of n-tuple of time series.
Input to this function is in the time domain
Parameters
----------
time_series : n*t float array
an array of n different time series of length t each
csd_method : dict, optional.
See :func:`get_spectra` documentation for details
Returns
-------
f : float array
The central frequencies for the frequency bands for which the spectra
are estimated
c : float array
This is a symmetric matrix with the coherencys of the signals. The
coherency of signal i and signal j is in f[i][j]. Note that f[i][j] =
f[j][i].conj()
Notes
-----
This is an implementation of equation (1) of Sun (2005):
.. math::
R_{xy} (\lambda) = \frac{f_{xy}(\lambda)}
{\sqrt{f_{xx} (\lambda) \cdot f_{yy}(\lambda)}}
F.T. Sun and L.M. Miller and M. D'Esposito (2005). Measuring temporal
dynamics of functional networks using phase spectrum of fMRI
data. Neuroimage, 28: 227-37.
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
# A container for the coherencys, with the size and shape of the expected
# output:
c = np.zeros((time_series.shape[0],
time_series.shape[0],
f.shape[0]), dtype=complex) # Make sure it's complex
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
c[i][j] = coherency_spec(fxy[i][j], fxy[i][i], fxy[j][j])
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return f, c
def coherency_spec(fxy, fxx, fyy):
r"""
Compute the coherency between the spectra of two time series.
Input to this function is in the frequency domain.
Parameters
----------
fxy : float array
The cross-spectrum of the time series
fyy,fxx : float array
The spectra of the signals
Returns
-------
complex array
the frequency-band-dependent coherency
See also
--------
:func:`coherency`
"""
return fxy / np.sqrt(fxx * fyy)
def coherence(time_series, csd_method=None):
r"""Compute the coherence between the spectra of an n-tuple of time_series.
Parameters of this function are in the time domain.
Parameters
----------
time_series : float array
an array of different time series with time as the last dimension
csd_method : dict, optional
See :func:`algorithms.spectral.get_spectra` documentation for details
Returns
-------
f : float array
The central frequencies for the frequency bands for which the spectra
are estimated
c : float array
This is a symmetric matrix with the coherencys of the signals. The
coherency of signal i and signal j is in f[i][j].
Notes
-----
This is an implementation of equation (2) of Sun (2005):
.. math::
Coh_{xy}(\lambda) = |{R_{xy}(\lambda)}|^2 =
\frac{|{f_{xy}(\lambda)}|^2}{f_{xx}(\lambda) \cdot f_{yy}(\lambda)}
F.T. Sun and L.M. Miller and M. D'Esposito (2005). Measuring temporal
dynamics of functional networks using phase spectrum of fMRI data.
Neuroimage, 28: 227-37.
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
# A container for the coherences, with the size and shape of the expected
# output:
c = np.zeros((time_series.shape[0],
time_series.shape[0],
f.shape[0]))
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
c[i][j] = coherence_spec(fxy[i][j], fxy[i][i], fxy[j][j])
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return f, c
def coherence_spec(fxy, fxx, fyy):
r"""
Compute the coherence between the spectra of two time series.
Parameters of this function are in the frequency domain.
Parameters
----------
fxy : array
The cross-spectrum of the time series
fyy, fxx : array
The spectra of the signals
Returns
-------
float : a frequency-band-dependent measure of the linear association
between the two time series
See also
--------
:func:`coherence`
"""
if not np.isrealobj(fxx):
fxx = np.real(fxx)
if not np.isrealobj(fyy):
fyy = np.real(fyy)
c = np.abs(fxy) ** 2 / (fxx * fyy)
return c
def coherency_regularized(time_series, epsilon, alpha, csd_method=None):
r"""
Compute a regularized measure of the coherence.
Regularization may be needed in order to overcome numerical imprecisions
Parameters
----------
time_series: float array
The time series data for which the regularized coherence is
calculated. Time as the last dimension.
epsilon: float
Small regularization parameter. Should be much smaller than any
meaningful value of coherence you might encounter
alpha: float
Large regularization parameter. Should be much larger than any
meaningful value of coherence you might encounter (preferably much
larger than 1).
csd_method: dict, optional.
See :func:`get_spectra` documentation for details
Returns
-------
f: float array
The central frequencies for the frequency bands for which the spectra
are estimated
c: float array
This is a symmetric matrix with the coherencys of the signals. The
coherency of signal i and signal j is in f[i][j]. Note that f[i][j] =
f[j][i].conj()
Notes
-----
The regularization scheme is as follows:
.. math::
Coh_{xy}^R = \frac{(\alpha f_{xx} + \epsilon) ^2}
{\alpha^{2}(f_{xx}+\epsilon)(f_{yy}+\epsilon)}
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
# A container for the coherences, with the size and shape of the expected
# output:
c = np.zeros((time_series.shape[0],
time_series.shape[0],
f.shape[0]), dtype=complex) # Make sure it's complex
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
c[i][j] = _coherency_reqularized(fxy[i][j], fxy[i][i],
fxy[j][j], epsilon, alpha)
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return f, c
def _coherency_reqularized(fxy, fxx, fyy, epsilon, alpha):
r"""
A regularized version of the calculation of coherency, which is more
robust to numerical noise than the standard calculation
Input to this function is in the frequency domain.
Parameters
----------
fxy, fxx, fyy: float arrays
The cross- and power-spectral densities of the two signals x and y
epsilon: float
First regularization parameter. Should be much smaller than any
meaningful value of coherence you might encounter
alpha: float
Second regularization parameter. Should be much larger than any
meaningful value of coherence you might encounter (preferably much
larger than 1).
Returns
-------
float array
The coherence values
"""
return (((alpha * fxy + epsilon)) /
np.sqrt(((alpha ** 2) * (fxx + epsilon) * (fyy + epsilon))))
def coherence_regularized(time_series, epsilon, alpha, csd_method=None):
r"""
Same as coherence, except regularized in order to overcome numerical
imprecisions
Parameters
----------
time_series: n-d float array
The time series data for which the regularized coherence is calculated
epsilon: float
Small regularization parameter. Should be much smaller than any
meaningful value of coherence you might encounter
alpha: float
large regularization parameter. Should be much larger than any
meaningful value of coherence you might encounter (preferably much
larger than 1).
csd_method: dict, optional.
See :func:`get_spectra` documentation for details
Returns
-------
f: float array
The central frequencies for the frequency bands for which the spectra
are estimated
c: n-d array
This is a symmetric matrix with the coherencys of the signals. The
coherency of signal i and signal j is in f[i][j].
Notes
-----
The regularization scheme is as follows:
.. math::
C_{x,y} = \frac{(\alpha f_{xx} + \epsilon)^2}
{\alpha^{2}((f_{xx}+\epsilon)(f_{yy}+\epsilon))}
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
# A container for the coherences, with the size and shape of the expected
# output:
c = np.zeros((time_series.shape[0],
time_series.shape[0],
f.shape[0]), complex)
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
c[i][j] = _coherence_reqularized(fxy[i][j], fxy[i][i],
fxy[j][j], epsilon, alpha)
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return f, c
def _coherence_reqularized(fxy, fxx, fyy, epsilon, alpha):
r"""A regularized version of the calculation of coherence, which is more
robust to numerical noise than the standard calculation.
Input to this function is in the frequency domain
Parameters
----------
fxy, fxx, fyy: float arrays
The cross- and power-spectral densities of the two signals x and y
epsilon: float
First regularization parameter. Should be much smaller than any
meaningful value of coherence you might encounter
alpha: float
Second regularization parameter. Should be much larger than any
meaningful value of coherence you might encounter (preferably much
larger than 1)
Returns
-------
float array
The coherence values
"""
return (((alpha * np.abs(fxy) + epsilon) ** 2) /
((alpha ** 2) * (fxx + epsilon) * (fyy + epsilon)))
def coherency_bavg(time_series, lb=0, ub=None, csd_method=None):
r"""
Compute the band-averaged coherency between the spectra of two time series.
Input to this function is in the time domain.
Parameters
----------
time_series: n*t float array
an array of n different time series of length t each
lb, ub: float, optional
the upper and lower bound on the frequency band to be used in averaging
defaults to 1,max(f)
csd_method: dict, optional.
See :func:`get_spectra` documentation for details
Returns
-------
c: float array
This is an upper-diagonal array, where c[i][j] is the band-averaged
coherency between time_series[i] and time_series[j]
Notes
-----
This is an implementation of equation (A4) of Sun(2005):
.. math::
\bar{Coh_{xy}} (\bar{\lambda}) =
\frac{\left|{\sum_\lambda{\hat{f_{xy}}}}\right|^2}
{\sum_\lambda{\hat{f_{xx}}}\cdot sum_\lambda{\hat{f_{yy}}}}
F.T. Sun and L.M. Miller and M. D'Esposito (2005). Measuring
temporal dynamics of functional networks using phase spectrum of fMRI
data. Neuroimage, 28: 227-37.
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
lb_idx, ub_idx = utils.get_bounds(f, lb, ub)
if lb == 0:
lb_idx = 1 # The lowest frequency band should be f0
c = np.zeros((time_series.shape[0],
time_series.shape[0]), dtype=complex)
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
c[i][j] = _coherency_bavg(fxy[i][j][lb_idx:ub_idx],
fxy[i][i][lb_idx:ub_idx],
fxy[j][j][lb_idx:ub_idx])
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return c
def _coherency_bavg(fxy, fxx, fyy):
r"""
Compute the band-averaged coherency between the spectra of two time series.
Input to this function is in the frequency domain.
Parameters
----------
fxy : float array
The cross-spectrum of the time series
fyy,fxx : float array
The spectra of the signals
Returns
-------
float
the band-averaged coherency
Notes
-----
This is an implementation of equation (A4) of [Sun2005]_:
.. math::
\bar{Coh_{xy}} (\bar{\lambda}) =
\frac{\left|{\sum_\lambda{\hat{f_{xy}}}}\right|^2}
{\sum_\lambda{\hat{f_{xx}}}\cdot sum_\lambda{\hat{f_{yy}}}}
.. [Sun2005] F.T. Sun and L.M. Miller and M. D'Esposito(2005). Measuring
temporal dynamics of functional networks using phase spectrum of fMRI
data. Neuroimage, 28: 227-37.
"""
# Average the phases and the magnitudes separately and then recombine:
p = np.angle(fxy)
p_bavg = np.mean(p)
m = np.abs(coherency_spec(fxy, fxx, fyy))
m_bavg = np.mean(m)
# Recombine according to z = r(cos(phi)+sin(phi)i):
return m_bavg * (np.cos(p_bavg) + np.sin(p_bavg) * 1j)
def coherence_bavg(time_series, lb=0, ub=None, csd_method=None):
r"""
Compute the band-averaged coherence between the spectra of two time series.
Input to this function is in the time domain.
Parameters
----------
time_series : float array
An array of time series, time as the last dimension.
lb, ub: float, optional
The upper and lower bound on the frequency band to be used in averaging
defaults to 1,max(f)
csd_method: dict, optional.
See :func:`get_spectra` documentation for details
Returns
-------
c : float
This is an upper-diagonal array, where c[i][j] is the band-averaged
coherency between time_series[i] and time_series[j]
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
lb_idx, ub_idx = utils.get_bounds(f, lb, ub)
if lb == 0:
lb_idx = 1 # The lowest frequency band should be f0
c = np.zeros((time_series.shape[0],
time_series.shape[0]))
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
c[i][j] = _coherence_bavg(fxy[i][j][lb_idx:ub_idx],
fxy[i][i][lb_idx:ub_idx],
fxy[j][j][lb_idx:ub_idx])
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return c
def _coherence_bavg(fxy, fxx, fyy):
r"""
Compute the band-averaged coherency between the spectra of two time series.
Input to this function is in the frequency domain
Parameters
----------
fxy : float array
The cross-spectrum of the time series
fyy,fxx : float array
The spectra of the signals
Returns
-------
float :
the band-averaged coherence
"""
if not np.isrealobj(fxx):
fxx = np.real(fxx)
if not np.isrealobj(fyy):
fyy = np.real(fyy)
return (np.abs(fxy.sum()) ** 2) / (fxx.sum() * fyy.sum())
def coherence_partial(time_series, r, csd_method=None):
r"""
Compute the band-specific partial coherence between the spectra of
two time series.
The partial coherence is the part of the coherence between x and
y, which cannot be attributed to a common cause, r.
Input to this function is in the time domain.
Parameters
----------
time_series: float array
An array of time-series, with time as the last dimension.
r: float array
This array represents the temporal sequence of the common cause to be
partialed out, sampled at the same rate as time_series
csd_method: dict, optional
See :func:`get_spectra` documentation for details
Returns
-------
f: array,
The mid-frequencies of the frequency bands in the spectral
decomposition
c: float array
The frequency dependent partial coherence between time_series i and
time_series j in c[i][j] and in c[j][i], with r partialed out
Notes
-----
This is an implementation of equation (2) of Sun (2004):
.. math::
Coh_{xy|r} = \frac{|{R_{xy}(\lambda) - R_{xr}(\lambda)
R_{ry}(\lambda)}|^2}{(1-|{R_{xr}}|^2)(1-|{R_{ry}}|^2)}
F.T. Sun and L.M. Miller and M. D'Esposito (2004). Measuring interregional
functional connectivity using coherence and partial coherence analyses of
fMRI data Neuroimage, 21: 647-58.
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
# Initialize c according to the size of f:
c = np.zeros((time_series.shape[0],
time_series.shape[0],
f.shape[0]), dtype=complex)
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
f, fxx, frr, frx = get_spectra_bi(time_series[i], r, csd_method)
f, fyy, frr, fry = get_spectra_bi(time_series[j], r, csd_method)
c[i, j] = coherence_partial_spec(fxy[i][j],
fxy[i][i],
fxy[j][j],
frx,
fry,
frr)
idx = tril_indices(time_series.shape[0], -1)
c[idx[0], idx[1], ...] = c[idx[1], idx[0], ...].conj() # Make it symmetric
return f, c
def coherence_partial_spec(fxy, fxx, fyy, fxr, fry, frr):
r"""
Compute the band-specific partial coherence between the spectra of
two time series. See :func:`partial_coherence`.
Input to this function is in the frequency domain.
Parameters
----------
fxy : float array
The cross-spectrum of the time series
fyy, fxx : float array
The spectra of the signals
fxr, fry : float array
The cross-spectra of the signals with the event
Returns
-------
float
the band-averaged coherency
"""
coh = coherency_spec
Rxr = coh(fxr, fxx, frr)
Rry = coh(fry, fyy, frr)
Rxy = coh(fxy, fxx, fyy)
return (((np.abs(Rxy - Rxr * Rry)) ** 2) /
((1 - ((np.abs(Rxr)) ** 2)) * (1 - ((np.abs(Rry)) ** 2))))
def coherency_phase_spectrum(time_series, csd_method=None):
r"""
Compute the phase spectrum of the cross-spectrum between two time series.
The parameters of this function are in the time domain.
Parameters
----------
time_series : n*t float array
The time series, with t, time, as the last dimension
Returns
-------
f : mid frequencies of the bands
p : an array with the pairwise phase spectrum between the time
series, where p[i][j] is the phase spectrum between time series[i] and
time_series[j]
Notes
-----
This is an implementation of equation (3) of Sun et al. (2005) [Sun2005]_:
.. math::
\phi(\lambda) = arg [R_{xy} (\lambda)] = arg [f_{xy} (\lambda)]
F.T. Sun and L.M. Miller and M. D'Esposito (2005). Measuring temporal
dynamics of functional networks using phase spectrum of fMRI data.
Neuroimage, 28: 227-37.
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
p = np.zeros((time_series.shape[0],
time_series.shape[0],
f.shape[0]))
for i in range(time_series.shape[0]):
for j in range(i + 1, time_series.shape[0]):
p[i][j] = np.angle(fxy[i][j])
p[j][i] = np.angle(fxy[i][j].conjugate())
return f, p
def coherency_phase_delay(time_series, lb=0, ub=None, csd_method=None):
"""
The temporal delay calculated from the coherency phase spectrum.
Parameters
----------
time_series: float array
The time-series data for which the delay is calculated.
lb, ub: float
Frequency boundaries (in Hz), for the domain over which the delays are
calculated. Defaults to 0-max(f)
csd_method : dict, optional.
See :func:`get_spectra`
Returns
-------
f : float array
The mid-frequencies for the frequency bands over which the calculation
is done.
p : float array
Pairwise temporal delays between time-series (in seconds).
"""
if csd_method is None:
csd_method = {'this_method': 'welch'} # The default
f, fxy = get_spectra(time_series, csd_method)
lb_idx, ub_idx = utils.get_bounds(f, lb, ub)
if lb_idx == 0:
lb_idx = 1
p = np.zeros((time_series.shape[0], time_series.shape[0],
f[lb_idx:ub_idx].shape[-1]))
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
p[i][j] = _coherency_phase_delay(f[lb_idx:ub_idx],
fxy[i][j][lb_idx:ub_idx])
p[j][i] = _coherency_phase_delay(
f[lb_idx:ub_idx],
fxy[i][j][lb_idx:ub_idx].conjugate())
return f[lb_idx:ub_idx], p
def _coherency_phase_delay(f, fxy):
r"""
Compute the phase delay between the spectra of two signals. The input to
this function is in the frequency domain.
Parameters
----------
f: float array
The frequencies
fxy : float array
The cross-spectrum of the time series
Returns
-------
float array
the phase delay (in sec) for each frequency band.
"""
return np.angle(fxy) / (2 * np.pi * f)
def correlation_spectrum(x1, x2, Fs=2 * np.pi, norm=False):
"""
Calculate the spectral decomposition of the correlation.
Parameters
----------
x1,x2: ndarray
Two arrays to be correlated. Same dimensions
Fs: float, optional
Sampling rate in Hz. If provided, an array of
frequencies will be returned.Defaults to 2
norm: bool, optional
When this is true, the spectrum is normalized to sum to 1
Returns
-------
f: ndarray
ndarray with the frequencies
ccn: ndarray
The spectral decomposition of the correlation
Notes
-----
This method is described in full in: D Cordes, V M Haughton, K Arfanakis, G
J Wendt, P A Turski, C H Moritz, M A Quigley, M E Meyerand (2000). Mapping
functionally related regions of brain with functional connectivity MR
imaging. AJNR American journal of neuroradiology 21:1636-44
"""
x1 = x1 - np.mean(x1)
x2 = x2 - np.mean(x2)
x1_f = fftpack.fft(x1)
x2_f = fftpack.fft(x2)
D = np.sqrt(np.sum(x1 ** 2) * np.sum(x2 ** 2))
n = x1.shape[0]
ccn = ((np.real(x1_f) * np.real(x2_f) +
np.imag(x1_f) * np.imag(x2_f)) /
(D * n))
if norm:
# Only half of the sum is sent back because of the freq domain
# symmetry.
ccn = ccn / np.sum(ccn) * 2
# XXX Does normalization make this strictly positive?
f = utils.get_freqs(Fs, n)
return f, ccn[0:(n // 2 + 1)]
# -----------------------------------------------------------------------
# Coherency calculated using cached spectra
# -----------------------------------------------------------------------
"""The idea behind this set of functions is to keep a cache of the windowed fft
calculations of each time-series in a massive collection of time-series, so
that this calculation doesn't have to be repeated each time a cross-spectrum is
calculated. The first function creates the cache and then, another function
takes the cached spectra and calculates PSDs and CSDs, which are then passed to
coherency_spec and organized in a data structure similar to the one
created by coherence"""
def cache_fft(time_series, ij, lb=0, ub=None,
method=None, prefer_speed_over_memory=False,
scale_by_freq=True):
"""compute and cache the windowed FFTs of the time_series, in such a way
that computing the psd and csd of any combination of them can be done
quickly.
Parameters
----------
time_series : float array
An ndarray with time-series, where time is the last dimension
ij: list of tuples
Each tuple in this variable should contain a pair of
indices of the form (i,j). The resulting cache will contain the fft of
time-series in the rows indexed by the unique elements of the union of i
and j
lb,ub: float
Define a frequency band of interest, for which the fft will be cached
method: dict, optional
See :func:`get_spectra` for details on how this is used. For this set
of functions, 'this_method' has to be 'welch'
Returns
-------
freqs, cache
where: cache =
{'FFT_slices':FFT_slices,'FFT_conj_slices':FFT_conj_slices,
'norm_val':norm_val}
Notes
-----
- For these functions, only the Welch windowed periodogram ('welch') is
available.
- Detrending the input is not an option here, in order to save
time on an empty function call.
"""
if method is None:
method = {'this_method': 'welch'} # The default
this_method = method.get('this_method', 'welch')
if this_method == 'welch':
NFFT = method.get('NFFT', 64)
Fs = method.get('Fs', 2 * np.pi)
window = method.get('window', mlab.window_hanning)
n_overlap = method.get('n_overlap', int(np.ceil(NFFT / 2.0)))
else:
e_s = "For cache_fft, spectral estimation method must be welch"
raise ValueError(e_s)
time_series = utils.zero_pad(time_series, NFFT)
# The shape of the zero-padded version:
n_channels, n_time_points = time_series.shape
# get all the unique channels in time_series that we are interested in by
# checking the ij tuples
all_channels = set()
for i, j in ij:
all_channels.add(i)
all_channels.add(j)
# for real time_series, ignore the negative frequencies
if np.iscomplexobj(time_series):
n_freqs = NFFT
else:
n_freqs = NFFT // 2 + 1
# Which frequencies
freqs = utils.get_freqs(Fs, NFFT)
# If there are bounds, limit the calculation to within that band,
# potentially include the DC component:
lb_idx, ub_idx = utils.get_bounds(freqs, lb, ub)
n_freqs = ub_idx - lb_idx
# Make the window:
if mlab.cbook.iterable(window):
assert(len(window) == NFFT)
window_vals = window
else:
window_vals = window(np.ones(NFFT, time_series.dtype))
# Each fft needs to be normalized by the square of the norm of the window
# and, for consistency with newer versions of mlab.csd (which, in turn, are
# consistent with Matlab), normalize also by the sampling rate:
if scale_by_freq:
# This is the normalization factor for one-sided estimation, taking
# into account the sampling rate. This makes the PSD a density
# function, with units of dB/Hz, so that integrating over
# frequencies gives you the RMS. (XXX this should be in the tests!).
norm_val = (np.abs(window_vals) ** 2).sum() * (Fs / 2)
else:
norm_val = (np.abs(window_vals) ** 2).sum() / 2
# cache the FFT of every windowed, detrended NFFT length segement
# of every channel. If prefer_speed_over_memory, cache the conjugate
# as well