-
Notifications
You must be signed in to change notification settings - Fork 40
/
connectivity.py
1312 lines (1072 loc) · 49.4 KB
/
connectivity.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
from functools import lru_cache, partial, wraps
from inspect import signature
from itertools import combinations
import numpy as np
from scipy.fftpack import ifft
from scipy.ndimage import label
from scipy.sparse.linalg import svds
from scipy.stats.mstats import linregress
from .minimum_phase_decomposition import minimum_phase_decomposition
from .statistics import (adjust_for_multiple_comparisons, coherence_bias,
fisher_z_transform, get_normal_distribution_p_values)
EXPECTATION = {
'time': partial(np.mean, axis=0),
'trials': partial(np.mean, axis=1),
'tapers': partial(np.mean, axis=2),
'time_trials': partial(np.mean, axis=(0, 1)),
'time_tapers': partial(np.mean, axis=(0, 2)),
'trials_tapers': partial(np.mean, axis=(1, 2)),
'time_trials_tapers': partial(np.mean, axis=(1, 2, 3)),
}
def non_negative_frequencies(axis):
'''Decorator that removes the negative frequencies.'''
def decorator(connectivity_measure):
@wraps(connectivity_measure)
def wrapper(*args, **kwargs):
measure = connectivity_measure(*args, **kwargs)
if measure is not None:
n_frequencies = measure.shape[axis]
non_neg_index = np.arange(0, (n_frequencies + 1) // 2)
return np.take(measure, indices=non_neg_index, axis=axis)
else:
return None
return wrapper
return decorator
class Connectivity:
'''Computes brain connectivity measures based on the cross spectral
matrix.
Spectral granger methods that require estimation of transfer function
and noise covariance use minimum phase decomposition [1] to decompose
the cross spectral matrix into square roots, which then can be used to
non-parametrically estimate the transfer function and noise covariance.
Attributes
----------
fourier_coefficients : array, shape (n_time_windows, n_trials,
n_tapers, n_fft_samples,
n_signals)
The compex-valued coefficients from a fourier transform. Note that
this is expected to be the two-sided fourier coefficients
(both the positive and negative lags). This is needed for the
Granger-based methods to work.
expectation_type : ('trials_tapers' | 'trials' | 'tapers')
How to average the cross spectral matrix. 'trials_tapers' averages
over the trials and tapers dimensions. 'trials' only averages over
the trials dimensions (leaving tapers) and 'tapers' only averages
over tapers (leaving trials).
frequencies : array, shape (n_fft_samples,)
time : array, shape (n_time_windows,)
Methods
-------
coherency
coherence_magnitude
coherence_phase
canonical_coherence
imaginary_coherence
phase_locking_value
phase_lag_index
weighted_phase_lag_index
debiased_squared_phase_lag_index
debiased_squared_weighted_phase_lag_index
pairwise_phase_consistency
directed_transfer_function
directed_coherence
partial_directed_coherence
generalized_partial_directed_coherence
direct_directed_transfer_function
group_delay
phase_lag_index
pairwise_spectral_granger_prediction
conditional_spectral_granger_prediction (Not implemented)
blockwise_spectral_granger_prediction (Not implemented)
References
----------
.. [1] Dhamala, M., Rangarajan, G., and Ding, M. (2008). Analyzing
information flow in brain networks with nonparametric Granger
causality. NeuroImage 41, 354-362.
'''
def __init__(self, fourier_coefficients,
expectation_type='trials_tapers', frequencies=None,
time=None):
self.fourier_coefficients = fourier_coefficients
self.expectation_type = expectation_type
self._frequencies = frequencies
self.time = time
@classmethod
def from_multitaper(cls, multitaper_instance,
expectation_type='trials_tapers'):
'''Construct connectivity class using a multitaper instance'''
return cls(
fourier_coefficients=multitaper_instance.fft(),
expectation_type=expectation_type,
time=multitaper_instance.time,
frequencies=multitaper_instance.frequencies
)
@property
@non_negative_frequencies(axis=0)
def frequencies(self):
if self._frequencies is not None:
return self._frequencies
@property
@lru_cache(maxsize=1)
def _power(self):
return self._expectation(
self.fourier_coefficients *
self.fourier_coefficients.conjugate()).real
@property
@lru_cache(maxsize=1)
def _cross_spectral_matrix(self):
'''The complex-valued linear association between fourier
coefficients at each frequency.
Returns
-------
cross_spectral_matrix : array, shape (n_time_windows, n_trials,
n_tapers, n_fft_samples,
n_signals, n_signals)
'''
fourier_coefficients = self.fourier_coefficients[..., np.newaxis]
return _complex_inner_product(fourier_coefficients,
fourier_coefficients)
@property
@lru_cache(maxsize=1)
def _minimum_phase_factor(self):
return minimum_phase_decomposition(
self._expectation(self._cross_spectral_matrix))
@property
@lru_cache(maxsize=1)
@non_negative_frequencies(axis=-3)
def _transfer_function(self):
return _estimate_transfer_function(self._minimum_phase_factor)
@property
@lru_cache(maxsize=1)
def _noise_covariance(self):
return _estimate_noise_covariance(self._minimum_phase_factor)
@property
@lru_cache(maxsize=1)
def _MVAR_Fourier_coefficients(self):
return np.linalg.inv(self._transfer_function)
@property
def _expectation(self):
return EXPECTATION[self.expectation_type]
@property
def n_observations(self):
axes = signature(self._expectation).parameters['axis'].default
if isinstance(axes, int):
return self.fourier_coefficients.shape[axes]
else:
return np.prod(
[self.fourier_coefficients.shape[axis]
for axis in axes])
@non_negative_frequencies(axis=-2)
def power(self):
return self._power
@non_negative_frequencies(axis=-3)
def coherency(self):
'''The complex-valued linear association between time series in the
frequency domain.
Returns
-------
complex_coherency : array, shape (..., n_fft_samples, n_signals,
n_signals)
'''
norm = np.sqrt(self._power[..., :, np.newaxis] *
self._power[..., np.newaxis, :])
norm[norm == 0] = np.nan
complex_coherencey = (
self._expectation(self._cross_spectral_matrix) / norm)
n_signals = self.fourier_coefficients.shape[-1]
diagonal_ind = np.arange(0, n_signals)
complex_coherencey[..., diagonal_ind, diagonal_ind] = np.nan
return complex_coherencey
def coherence_phase(self):
'''The phase angle of the complex coherency.
Returns
-------
phase : array, shape (..., n_fft_samples, n_signals, n_signals)
'''
return np.angle(self.coherency())
def coherence_magnitude(self):
'''The magnitude of the complex coherency.
Note that this is not the magnitude squared coherence.
Returns
-------
magnitude : array, shape (..., n_fft_samples, n_signals, n_signals)
'''
return _squared_magnitude(self.coherency())
@non_negative_frequencies(axis=-3)
def imaginary_coherence(self):
'''The normalized imaginary component of the cross-spectrum.
Projects the cross-spectrum onto the imaginary axis to mitigate the
effect of volume-conducted dependencies. Assumes volume-conducted
sources arrive at sensors at the same time, resulting in
a cross-spectrum with phase angle of 0 (perfectly in-phase) or \pi
(anti-phase) if the sensors are on opposite sides of a dipole
source. With the imaginary coherence, in-phase and anti-phase
associations are set to zero.
Returns
-------
imaginary_coherence_magnitude : array, shape (..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Nolte, G., Bai, O., Wheaton, L., Mari, Z., Vorbach, S., and
Hallett, M. (2004). Identifying true brain interaction from
EEG data using the imaginary part of coherency. Clinical
Neurophysiology 115, 2292-2307.
'''
return np.abs(
self._expectation(self._cross_spectral_matrix).imag /
np.sqrt(self._power[..., :, np.newaxis] *
self._power[..., np.newaxis, :]))
def canonical_coherence(self, group_labels):
'''Finds the maximal coherence between each combination of groups.
The canonical coherence finds two sets of weights such that the
coherence between the linear combination of group1 and the linear
combination of group2 is maximized.
Parameters
----------
group_labels : array-like, shape (n_signals,)
Links each signal to a group.
Returns
-------
canonical_coherence : array, shape (n_time_samples, n_fft_samples,
n_groups, n_groups)
The maximimal coherence for each group pair
labels : array, shape (n_groups,)
The sorted unique group labels that correspond to `n_groups`
References
----------
.. [1] Stephen, E.P. (2015). Characterizing dynamically evolving
functional networks in humans with application to speech.
Boston University.
'''
labels = np.unique(group_labels)
n_frequencies = self.fourier_coefficients.shape[-2]
non_negative_frequencies = np.arange(0, (n_frequencies + 1) // 2)
fourier_coefficients = self.fourier_coefficients[
..., non_negative_frequencies, :]
normalized_fourier_coefficients = [
_normalize_fourier_coefficients(
fourier_coefficients[..., np.in1d(group_labels, label)])
for label in labels]
n_groups = len(labels)
new_shape = (self.time.size, self.frequencies.size, n_groups,
n_groups)
magnitude = _squared_magnitude(np.stack([
_estimate_canonical_coherence(
fourier_coefficients1, fourier_coefficients2)
for fourier_coefficients1, fourier_coefficients2
in combinations(normalized_fourier_coefficients, 2)
], axis=-1))
canonical_coherence_magnitude = np.full(new_shape, np.nan)
group_combination_ind = np.array(
list(combinations(np.arange(n_groups), 2)))
canonical_coherence_magnitude[
..., group_combination_ind[:, 0],
group_combination_ind[:, 1]] = magnitude
canonical_coherence_magnitude[
..., group_combination_ind[:, 1],
group_combination_ind[:, 0]] = magnitude
return canonical_coherence_magnitude, labels
def global_coherence(self, max_rank=1):
'''The linear combinations of signals that capture the most coherent
power at each frequency and time window.
This is a frequency domain analog of PCA over signals at a given
frequency/time window.
Parameters
----------
max_rank : int, optional
The number of components to keep (like the number of PC dimensions)
Returns
-------
global_coherence : ndarray, shape (n_time_windows,
n_fft_samples,
n_components)
The vector of global coherences (square of the singular values)
unnormalized_global_coherence : ndarray, shape (n_time_windows,
n_fft_samples,
n_signals,
n_components)
The (unnormalized) global coherence vectors
References
----------
.. [1] Cimenser, A., Purdon, P.L., Pierce, E.T., Walsh, J.L.,
Salazar-Gomez, A.F., Harrell, P.G., Tavares-Stoeckel, C.,
Habeeb, K., and Brown, E.N. (2011). Tracking brain states under
general anesthesia by using global coherence analysis.
Proceedings of the National Academy of Sciences 108, 8832–8837.
'''
(n_time_windows, n_trials, n_tapers,
n_fft_samples, n_signals) = self.fourier_coefficients.shape
# S - singular values
global_coherence = np.zeros((n_time_windows, n_fft_samples, max_rank))
# U - rotation
unnormalized_global_coherence = np.zeros(
(n_time_windows, n_fft_samples, n_signals, max_rank),
dtype=np.complex128)
for time_ind in range(n_time_windows):
for freq_ind in range(n_fft_samples):
# reshape to (n_signals, n_trials * n_tapers)
fourier_coefficients = (
self.fourier_coefficients[time_ind, :, :, freq_ind, :]
.reshape((n_trials * n_tapers, n_signals))
.T
)
(global_coherence[time_ind, freq_ind],
unnormalized_global_coherence[time_ind, freq_ind]
) = _estimate_global_coherence(fourier_coefficients,
max_rank=max_rank)
return global_coherence, unnormalized_global_coherence
@non_negative_frequencies(axis=-3)
def phase_locking_value(self):
'''The cross-spectrum with the power for each signal scaled to
a magnitude of 1.
The phase locking value attempts to mitigate power differences
between realizations (tapers or trials) by treating all values of
the cross-spectrum as the same power. This has the effect of
downweighting high power realizations and upweighting low power
realizations.
Returns
-------
phase_locking_value : array, shape (..., n_fft_samples, n_signals,
n_signals)
References
----------
.. [1] Lachaux, J.-P., Rodriguez, E., Martinerie, J., Varela, F.J.,
and others (1999). Measuring phase synchrony in brain
signals. Human Brain Mapping 8, 194-208.
'''
return self._expectation(
self._cross_spectral_matrix /
np.abs(self._cross_spectral_matrix))
@non_negative_frequencies(axis=-3)
def phase_lag_index(self):
'''A non-parametric synchrony measure designed to mitigate power
differences between realizations (tapers, trials) and
volume-conduction.
The phase lag index is the average sign of the imaginary
component of the cross-spectrum. The imaginary component sets
in-phase or anti-phase signals to zero and the sign scales it to
have the same magnitude regardless of phase.
Note that this is the signed version of the phase lag index. In order
to obtain the unsigned version, as in [1], take the absolute value
of this quantity.
Returns
-------
phase_lag_index : array, shape (..., n_fft_samples, n_signals,
n_signals)
References
----------
.. [1] Stam, C.J., Nolte, G., and Daffertshofer, A. (2007). Phase
lag index: Assessment of functional connectivity from multi
channel EEG and MEG with diminished bias from common
sources. Human Brain Mapping 28, 1178-1193.
'''
return self._expectation(np.sign(self._cross_spectral_matrix.imag))
@non_negative_frequencies(-3)
def weighted_phase_lag_index(self):
'''Weighted average of the phase lag index using the imaginary
coherency magnitudes as weights.
Returns
-------
weighted_phase_lag_index : array, shape (..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Vinck, M., Oostenveld, R., van Wingerden, M., Battaglia, F.,
and Pennartz, C.M.A. (2011). An improved index of
phase-synchronization for electrophysiological data in the
presence of volume-conduction, noise and sample-size bias.
NeuroImage 55, 1548-1565.
'''
weights = self._expectation(
np.abs(self._cross_spectral_matrix.imag))
weights[weights < np.finfo(float).eps] = 1
return self._expectation(
self._cross_spectral_matrix.imag) / weights
def debiased_squared_phase_lag_index(self):
'''The square of the phase lag index corrected for the positive
bias induced by using the magnitude of the complex cross-spectrum.
Returns
-------
phase_lag_index : array, shape (..., n_fft_samples, n_signals,
n_signals)
References
----------
.. [1] Vinck, M., Oostenveld, R., van Wingerden, M., Battaglia, F.,
and Pennartz, C.M.A. (2011). An improved index of
phase-synchronization for electrophysiological data in the
presence of volume-conduction, noise and sample-size bias.
NeuroImage 55, 1548-1565.
'''
n_observations = self.n_observations
return ((n_observations * self.phase_lag_index() ** 2 - 1.0) /
(n_observations - 1.0))
@non_negative_frequencies(-3)
def debiased_squared_weighted_phase_lag_index(self):
'''The square of the weighted phase lag index corrected for the
positive bias induced by using the magnitude of the complex
cross-spectrum.
Returns
-------
weighted_phase_lag_index : array, shape (..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Vinck, M., Oostenveld, R., van Wingerden, M., Battaglia, F.,
and Pennartz, C.M.A. (2011). An improved index of
phase-synchronization for electrophysiological data in the
presence of volume-conduction, noise and sample-size bias.
NeuroImage 55, 1548-1565.
'''
n_observations = self.n_observations
imaginary_cross_spectral_matrix_sum = self._expectation(
self._cross_spectral_matrix.imag) * n_observations
squared_imaginary_cross_spectral_matrix_sum = self._expectation(
self._cross_spectral_matrix.imag ** 2) * n_observations
imaginary_cross_spectral_matrix_magnitude_sum = self._expectation(
np.abs(self._cross_spectral_matrix.imag)) * n_observations
weights = (imaginary_cross_spectral_matrix_magnitude_sum ** 2 -
squared_imaginary_cross_spectral_matrix_sum)
weights[weights == 0] = np.nan
return (imaginary_cross_spectral_matrix_sum ** 2 -
squared_imaginary_cross_spectral_matrix_sum) / weights
def pairwise_phase_consistency(self):
'''The square of the phase locking value corrected for the
positive bias induced by using the magnitude of the complex
cross-spectrum.
Returns
-------
phase_locking_value : array, shape (..., n_fft_samples, n_signals,
n_signals)
References
----------
.. [1] Vinck, M., van Wingerden, M., Womelsdorf, T., Fries, P., and
Pennartz, C.M.A. (2010). The pairwise phase consistency: A
bias-free measure of rhythmic neuronal synchronization.
NeuroImage 51, 112-122.
'''
n_observations = self.n_observations
plv_sum = self.phase_locking_value() * n_observations
ppc = ((plv_sum * plv_sum.conjugate() - n_observations) /
(n_observations ** 2 - n_observations))
return ppc.real
def pairwise_spectral_granger_prediction(self):
'''The amount of power at a node in a frequency explained by (is
predictive of) the power at other nodes.
Also known as spectral granger causality.
References
----------
.. [1] Geweke, J. (1982). Measurement of Linear Dependence and
Feedback Between Multiple Time Series. Journal of the
American Statistical Association 77, 304.
'''
cross_spectral_matrix = self._expectation(
self._cross_spectral_matrix)
n_signals = cross_spectral_matrix.shape[-1]
total_power = self.power()
n_frequencies = cross_spectral_matrix.shape[-3]
non_neg_index = np.arange(0, (n_frequencies + 1) // 2)
new_shape = list(cross_spectral_matrix.shape)
new_shape[-3] = non_neg_index.size
predictive_power = np.empty(new_shape)
for pair_indices in combinations(range(n_signals), 2):
pair_indices = np.array(pair_indices)[:, np.newaxis]
try:
minimum_phase_factor = (
minimum_phase_decomposition(
cross_spectral_matrix[
..., pair_indices, pair_indices.T]))
transfer_function = _estimate_transfer_function(
minimum_phase_factor)[..., non_neg_index, :, :]
rotated_covariance = _remove_instantaneous_causality(
_estimate_noise_covariance(minimum_phase_factor))
predictive_power[..., pair_indices, pair_indices.T] = (
_estimate_predictive_power(
total_power[..., pair_indices[:, 0]],
rotated_covariance, transfer_function))
except np.linalg.LinAlgError:
predictive_power[
..., pair_indices, pair_indices.T] = np.nan
diagonal_ind = np.diag_indices(n_signals)
predictive_power[..., diagonal_ind[0], diagonal_ind[1]] = np.nan
return predictive_power
def conditional_spectral_granger_prediction(self):
raise NotImplementedError
def blockwise_spectral_granger_prediction(self):
raise NotImplementedError
def directed_transfer_function(self):
'''The transfer function coupling strength normalized by the total
influence of other signals on that signal (inflow).
Characterizes the direct and indirect coupling to a node.
Returns
-------
directed_transfer_function : array, shape (..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Kaminski, M., and Blinowska, K.J. (1991). A new method of
the description of the information flow in the brain
structures. Biological Cybernetics 65, 203-210.
'''
return _squared_magnitude(
self._transfer_function /
_total_inflow(self._transfer_function))
def directed_coherence(self):
'''The transfer function coupling strength normalized by the total
influence of other signals on that signal (inflow).
This measure is the same as the directed transfer function but the
signal inflow is scaled by the noise variance.
Returns
-------
directed_coherence : array, shape (..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Baccala, L., Sameshima, K., Ballester, G., Do Valle, A., and
Timo-Iaria, C. (1998). Studying the interaction between
brain structures via directed coherence and Granger
causality. Applied Signal Processing 5, 40.
'''
noise_variance = _get_noise_variance(self._noise_covariance)
return (np.sqrt(noise_variance) *
_squared_magnitude(self._transfer_function) /
_total_inflow(self._transfer_function, noise_variance))
def partial_directed_coherence(self):
'''The transfer function coupling strength normalized by its
strength of coupling to other signals (outflow).
The partial directed coherence tries to regress out the influence
of other observed signals, leaving only the direct coupling between
two signals.
Returns
-------
partial_directed_coherence : array, shape (..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Baccala, L.A., and Sameshima, K. (2001). Partial directed
coherence: a new concept in neural structure determination.
Biological Cybernetics 84, 463-474.
'''
return _squared_magnitude(
self._MVAR_Fourier_coefficients /
_total_outflow(self._MVAR_Fourier_coefficients))
def generalized_partial_directed_coherence(self):
'''The transfer function coupling strength normalized by its
strength of coupling to other signals (outflow).
The partial directed coherence tries to regress out the influence
of other observed signals, leaving only the direct coupling between
two signals.
The generalized partial directed coherence scales the relative
strength of coupling by the noise variance.
Returns
-------
generalized_partial_directed_coherence : array,
shape (..., n_fft_samples,
n_signals,
n_signals)
References
----------
.. [1] Baccala, L.A., Sameshima, K., and Takahashi, D.Y. (2007).
Generalized partial directed coherence. In Digital Signal
Processing, 2007 15th International Conference on, (IEEE),
pp. 163-166.
'''
noise_variance = _get_noise_variance(self._noise_covariance)
return _squared_magnitude(
self._MVAR_Fourier_coefficients /
np.sqrt(noise_variance) / _total_outflow(
self._MVAR_Fourier_coefficients, noise_variance))
def direct_directed_transfer_function(self):
'''A combination of the directed transfer function estimate of
directional influence between signals and the partial coherence's
accounting for the influence of other signals.
Returns
-------
direct_directed_transfer_function : array, shape
(..., n_fft_samples,
n_signals, n_signals)
References
----------
.. [1] Korzeniewska, A., Manczak, M., Kaminski,
M., Blinowska, K.J., and Kasicki, S. (2003). Determination
of information flow direction among brain structures by a
modified directed transfer function (dDTF) method.
Journal of Neuroscience Methods 125, 195-207.
'''
full_frequency_DTF = (
self._transfer_function /
_total_inflow(self._transfer_function, axis=(-1, -3)))
return (np.abs(full_frequency_DTF) *
np.sqrt(self.partial_directed_coherence()))
def group_delay(self, frequencies_of_interest=None,
frequency_resolution=None,
significance_threshold=0.05):
'''The average time-delay of a broadband signal.
Parameters
----------
frequencies_of_interest : array-like, shape (2,)
frequencies : array-like, shape (n_fft_samples,)
frequency_resolution : float
Returns
-------
delay : array, shape (..., n_signals, n_signals)
slope : array, shape (..., n_signals, n_signals)
r_value : array, shape (..., n_signals, n_signals)
References
----------
.. [1] Gotman, J. (1983). Measurement of small time differences
between EEG channels: method and application to epileptic
seizure propagation. Electroencephalography and Clinical
Neurophysiology 56, 501-514.
'''
frequencies = self.frequencies
frequency_difference = frequencies[1] - frequencies[0]
independent_frequency_step = _get_independent_frequency_step(
frequency_difference, frequency_resolution)
bandpassed_coherency, bandpassed_frequencies = _bandpass(
self.coherency(), frequencies, frequencies_of_interest)
bias = coherence_bias(self.n_observations)
n_signals = bandpassed_coherency.shape[-1]
signal_combination_ind = np.array(
list(combinations(np.arange(n_signals), 2)))
bandpassed_coherency = bandpassed_coherency[
..., signal_combination_ind[:, 0],
signal_combination_ind[:, 1]]
is_significant = _find_significant_frequencies(
bandpassed_coherency, bias, independent_frequency_step,
significance_threshold=significance_threshold)
coherence_phase = np.ma.masked_array(
np.unwrap(np.angle(bandpassed_coherency), axis=-2),
mask=~is_significant)
def _linear_regression(response):
return linregress(bandpassed_frequencies, y=response)
regression_results = np.ma.apply_along_axis(
_linear_regression, -2, coherence_phase)
new_shape = (
*bandpassed_coherency.shape[:-2], n_signals, n_signals)
slope = np.full(new_shape, np.nan)
slope[..., signal_combination_ind[:, 0],
signal_combination_ind[:, 1]] = np.array(
regression_results[..., 0, :], dtype=np.float)
slope[..., signal_combination_ind[:, 1],
signal_combination_ind[:, 0]] = -1 * np.array(
regression_results[..., 0, :], dtype=np.float)
delay = slope / (2 * np.pi)
r_value = np.ones(new_shape)
r_value[..., signal_combination_ind[:, 0],
signal_combination_ind[:, 1]] = np.array(
regression_results[..., 2, :], dtype=np.float)
r_value[..., signal_combination_ind[:, 1],
signal_combination_ind[:, 0]] = np.array(
regression_results[..., 2, :], dtype=np.float)
return delay, slope, r_value
def delay(self, frequencies_of_interest=None,
frequency_resolution=None,
significance_threshold=0.05, n_range=3):
'''Find a range of possible delays from the coherence phase.
The delay (and phase) at each frequency is indistinguishable from
2 \pi phase jumps, but we can look at a range of possible delays
and see which one is most likely.
Parameters
----------
frequencies_of_interest : array-like, shape (2,)
frequencies : array-like, shape (n_fft_samples,)
frequency_resolution : float
n_range : int
Number of phases to consider.
Returns
-------
possible_delays : array, shape (..., n_frequencies,
(n_range * 2) + 1, n_signals,
n_signals)
'''
frequencies = self.frequencies
frequency_difference = frequencies[1] - frequencies[0]
independent_frequency_step = _get_independent_frequency_step(
frequency_difference, frequency_resolution)
bandpassed_coherency, bandpassed_frequencies = _bandpass(
self.coherency(), frequencies, frequencies_of_interest)
bias = coherence_bias(self.n_observations)
n_signals = bandpassed_coherency.shape[-1]
signal_combination_ind = np.array(
list(combinations(np.arange(n_signals), 2)))
bandpassed_coherency = bandpassed_coherency[
..., signal_combination_ind[:, 0],
signal_combination_ind[:, 1]]
is_significant = _find_significant_frequencies(
bandpassed_coherency, bias, independent_frequency_step,
significance_threshold=significance_threshold)
coherence_phase = np.ma.masked_array(
np.unwrap(np.angle(bandpassed_coherency), axis=-2),
mask=~is_significant)
possible_range = 2 * np.pi * np.arange(-n_range, n_range + 1)
delays = np.rollaxis((
possible_range + coherence_phase[..., np.newaxis]) /
(2 * np.pi), -1, -2)
new_shape = (
*bandpassed_coherency.shape[:-1], len(possible_range),
n_signals, n_signals)
possible_delays = np.full(new_shape, np.nan)
possible_delays[..., signal_combination_ind[:, 0],
signal_combination_ind[:, 1]] = delays
possible_delays[..., signal_combination_ind[:, 1],
signal_combination_ind[:, 0]] = -delays
return possible_delays
def phase_slope_index(self, frequencies_of_interest=None,
frequency_resolution=None):
'''The weighted average of slopes of a broadband signal projected
onto the imaginary axis.
The phase slope index finds the complex weighted average of the
coherency between frequencies where the weights correspond to the
magnitude of the coherency at that frequency. This is projected
on to the imaginary axis to avoid volume conduction effects.
Parameters
----------
frequencies_of_interest : array-like, shape (2,)
frequencies : array-like, shape (n_fft_samples,)
frequency_resolution : float
Returns
-------
phase_slope_index : array, shape (..., n_signals, n_signals)
References
----------
.. [1] Nolte, G., Ziehe, A., Nikulin, V.V., Schlogl, A., Kramer,
N., Brismar, T., and Muller, K.-R. (2008). Robustly
Estimating the Flow Direction of Information in Complex
Physical Systems. Physical Review Letters 100.
'''
frequencies = self.frequencies
bandpassed_coherency, bandpassed_frequencies = _bandpass(
self.coherency(), frequencies, frequencies_of_interest)
frequency_difference = frequencies[1] - frequencies[0]
independent_frequency_step = _get_independent_frequency_step(
frequency_difference, frequency_resolution)
frequency_index = np.arange(0, bandpassed_frequencies.shape[0],
independent_frequency_step)
bandpassed_coherency = bandpassed_coherency[
..., frequency_index, :, :]
return _inner_combination(bandpassed_coherency).imag
def _inner_combination(data, axis=-3):
'''Takes the inner product of all possible pairs of a
dimension without regard to order (combinations)'''
combination_index = np.array(
list(combinations(range(data.shape[axis]), 2)))
combination_slice1 = np.take(data, combination_index[:, 0], axis)
combination_slice2 = np.take(data, combination_index[:, 1], axis)
return (combination_slice1.conjugate() * combination_slice2).sum(
axis=axis)
def _estimate_noise_covariance(minimum_phase):
'''Given a matrix square root of the cross spectral matrix (
minimum phase factor), non-parametrically estimate the noise covariance
of a multivariate autoregressive model (MVAR).
Parameters
----------
minimum_phase : array, shape (n_time_windows, n_fft_samples,
n_signals, n_signals)
The matrix square root of a cross spectral matrix.
Returns
-------
noise_covariance : array, shape (n_time_windows, n_signals, n_signals)
The noise covariance of a MVAR model.
References
----------
.. [1] Dhamala, M., Rangarajan, G., and Ding, M. (2008). Analyzing
information flow in brain networks with nonparametric Granger
causality. NeuroImage 41, 354-362.
'''
inverse_fourier_coefficients = ifft(minimum_phase, axis=-3).real
return _complex_inner_product(
inverse_fourier_coefficients[..., 0, :, :],
inverse_fourier_coefficients[..., 0, :, :]).real
def _estimate_transfer_function(minimum_phase):
'''Given a matrix square root of the cross spectral matrix (
minimum phase factor), non-parametrically estimate the transfer
function of a multivariate autoregressive model (MVAR).
Parameters
----------
minimum_phase : array, shape (n_time_windows, n_fft_samples,
n_signals, n_signals)
The matrix square root of a cross spectral matrix.
Returns
-------
transfer_function : array, shape (n_time_windows, n_fft_samples,
n_signals, n_signals)
The transfer function of a MVAR model.
References
----------
.. [1] Dhamala, M., Rangarajan, G., and Ding, M. (2008). Analyzing
information flow in brain networks with nonparametric Granger
causality. NeuroImage 41, 354-362.
'''
inverse_fourier_coefficients = ifft(minimum_phase, axis=-3).real
return np.matmul(
minimum_phase,
np.linalg.inv(inverse_fourier_coefficients[..., 0:1, :, :]))
def _estimate_predictive_power(total_power, rotated_covariance,
transfer_function):
intrinsic_power = (total_power[..., np.newaxis] -
rotated_covariance[..., np.newaxis, :, :] *
_squared_magnitude(transfer_function))
intrinsic_power[intrinsic_power == 0] = np.finfo(float).eps
predictive_power = (
np.log(total_power[..., np.newaxis]) - np.log(intrinsic_power))
predictive_power[predictive_power <= 0] = np.nan
return predictive_power
def _squared_magnitude(x):
return np.abs(x) ** 2
def _complex_inner_product(a, b):
'''Measures the orthogonality (similarity) of complex arrays in
the last two dimensions.'''
return np.matmul(a, _conjugate_transpose(b))
def _remove_instantaneous_causality(noise_covariance):
'''Rotates the noise covariance so that the effect of instantaneous
signals (like those caused by volume conduction) are removed.
x -> y: var(x) - (cov(x,y) ** 2 / var(y))
y -> x: var(y) - (cov(x,y) ** 2 / var(x))
Parameters
----------
noise_covariance : array, shape (..., n_signals, n_signals)